Keycloak API always returns 401

Is that not the correct way to include the token?

This is a correct way.

You just do something incorrectly. Please, refer for an example from keycloak-request-token Node.js module:

https://github.com/keycloak/keycloak-request-token/blob/master/index.js#L43

You use

client_id : 'test-realm'

but there is

client_id: 'admin-cli' 

there.

Also, to create a user, you should use

'Content-Type': 'application/json'

You can refer for Node.js examples of Keycloak REST API here:

https://github.com/v-ladynev/keycloak-nodejs-example/blob/master/lib/adminClient.js

Examples of other useful stuff like:

  • custom login
  • storing Keycloak token in the cookies
  • centralized permission middleware

can be found in the same project: keycloak-nodejs-example


I got a 401 error because I generated the offline token by using http://localhost:8080 and then I tried to request the api by using http://keycloak:8080 which is not allowed. Unfortunately the log doesn't tell you that.

To debug JWT tokens I recommend https://jwt.io/