node.jskeycloakkeycloak-connect

Logging into Keycloak from NodeJS: 400 Bad Request


I'm trying to log in into Keycloak from NodeJS code, and I'm struggling with finding the working example.

The documentation on https://www.keycloak.org/docs/latest/securing_apps/index.html#_nodejs_adapter is incomplete and doesn't describe the most important thing, how do you actually log in.

I've tinkered my example from the rudimentary information on the keycloak docs, and the tests from keycloak-nodejs-connect:

"keycloak-connect": "15.0.2",
"express-session": "1.17.2",

const Keycloak = require('keycloak-connect');
const session = require('express-session');

const keycloakConfig = {
  serverUrl: "http://keycloak.intern/auth",
  realm: "client-realm",
  clientId: "test-client",
  bearerOnly: true
}
const memoryStore = new session.MemoryStore();
const keycloak = new Keycloak({store: memoryStore}, keycloakConfig)

async function loginUser(username, password) {
  return await keycloak.grantManager.obtainDirectly(username, password).then(grant => {
    return grant
  })
}
const main = async () => {
  let grant = await loginUser('testuser@localhost.com', "test_password")

}

main().then(()=>{
  process.exit(0)
}, (err)=>{
  console.error(err)
  process.exit(1)
})

However, I'm getting errror:

Error: 400:Bad Request

On the server side, I see log:

2021-11-19T10:16:49,312+01:00 WARN [org.keycloak.events] (default task-56) type=LOGIN_ERROR, realmId=client-realm, clientId=test-client, userId=null, ipAddress=192.168.111.2222, error=not_allowed, auth_method=oauth_credentials, grant_type=password, client_auth_method=client-secret

So the keycloak API is called, however, the username is somehow not correctly given.

The signature of the method is OK, it gets the username, how it expects.

What I'm missing here?


Solution

  • Error not_allowed indicates that direct grant is not allowed. Enable Direct Access Grants Enabled in the test-client Keycloak client configuration.