1

I have a web app with Angular in Frontend, NodeJS in Backend and Keycloak as an identity management solution.

My Frontend stores the access- and id-token. All the NodeJS routes are protected by keycloak (bearer only). That's why I intercepted on each of my requests the access-token as bearer in the header:

setHeaders: { Authorization: 'Bearer ' + this.oauthService.getAccessToken() }

Now I'm able to authorize the requests, but how I can get the user Information in Backend?

At least only an ID is necessary to make user-dependent DB requests. Is it possible to get any information from the access token?

Or does the NodeJS connector (keycloak-connect) get this information itself so that I can save it in a session? What is the best way to do it?

Sandeep Patel
  • 4,815
  • 3
  • 21
  • 37
Nico Schuck
  • 832
  • 3
  • 15
  • 32

1 Answers1

1

if I am not wrong, Access token is JWT token and you will be able to decode is as bellow:

const jwt = require('jsonwebtoken');
var tokendetails = jwt.decode(token)

Alternatively in Keycloakconnect middleware, you can get details as below

app.get('/apis/me', keycloak.enforcer('user:profile', {response_mode: 'token'}), function (req, res) {
       ​let  tokenDetails = req.kauth.grant

   ​})

I have not tested so I am not 100% sure but I think you should be able to get username this way:

req.kauth.grant.access_token.content.preferred_username

Another way you could to something like this:

const request = require('request');
const options = {
  url: `${authServerUrl}/realms/${encodeURIComponent(realm)}/account`;,
  headers: {
    'Authorization':'bearer '+token
  }
};

request(options,function(error, response, body){

   if(!error) { 
    let userProfile = body
   }
})

Below resources might help you : https://www.keycloak.org/docs/latest/securing_apps/index.html#_nodejs_adapter https://github.com/v-ladynev/keycloak-nodejs-example/blob/master/lib/keyCloakService.js

Sandeep Patel
  • 4,815
  • 3
  • 21
  • 37