louie007 / passport-keycloak-oauth2-oidc

A Passport.js strategy for authenticating with Keycloak using the OAuth2/OIDC API
MIT License
27 stars 12 forks source link

Get Roles #1

Closed BravoJuliett closed 5 years ago

BravoJuliett commented 5 years ago

I cannot seem to figure out how to get the user's roles from keycloak is there something I am doing wrong here:

passport.use(new KeyCloakStrategy({
    clientID: keys.oauth2.clientID,
    realm: "development",
    publicClient: 'false',
    clientSecret: keys.oauth2.clientSecret,
    sslRequired: 'none',
    authServerURL: 'http://example.com/auth',
    callbackURL: '/auth/oauth2/redirect'
  }, (accessToken, refreshToken, roles, done) => {
    console.log(roles);
}));
router.get('/oauth2', passport.authenticate('keycloak', {
    scope: ['roles']
  }));

router.get('/oauth2/redirect',
  passport.authenticate('keycloak', { failureRedirect: '/login' }),
  (req, res) => {
    res.redirect('/profile/');
  });

and I get this when I log either roles or profile to console in the first code block:

{ realm: 'development',
  provider: 'keycloak',
  id: '<user-id>',
  username: '<username>',
  email: '<email>',
  name: '<name>',
  given_name: '<name>',
  email_verified: true,
  _json:
   { sub: '<user-id>',
     email_verified: true,
     name: '<username>',
     preferred_username: '<username>',
     given_name: '<user>',
     family_name: '<name>',
     email: '<email>' } }

as you can see roles are no where to be found. Any help would be appreciated. Thanks.

louie007 commented 5 years ago

By default, Keycloak returns Roles information within AccessToken.

If you are wondering to fetch Roles (e.g. realm_access roles, resource_access roles etc) within UserInfo endpoint, please make sure that Keycloak returns those claims .

To add these claims to the UserInfo endpoint, edit the roles settings in the Client Scopes:

Clients Scopes -> roles -> settings:

and in the client roles mappers settings, an example mapping :