0

I have been trying to solve this for several days. I followed the tutorial in Auth0's documentation.

After decoding the token with express-jwt:

export let headerJWTCheck = expressJwt({
    secret: '*************************',
    audience: '******************************'
});

the content of req.user doesn't have the profile and roles that I need for role restrictions in the API.

Instead the content is in the form:

{ iss: 'https://******.eu.auth0.com/',
  sub: 'google-oauth2|***********************',
  aud: '********************',
  exp: **************,
  iat: **************}

In the front end I already get the user profile information I need, but I can't progress beyond that.

I'm using a function to restric the roles:

export function requireRole(role: string) {
return function (req, res, next) {
    console.log(req.user);
    var appMetadata = req.user.profile._json.app_metadata || {};
    var roles = appMetadata.roles || [];

    if (roles.indexOf(role) != -1) {
        next();
    } else {
        res.redirect('/unauthorized');
    }
}

but req.user.profile is always undefined.

In the main express application definition I have:

app.use(cookieParser());
app.use(session({
    .................
}));
configurePassport();

app.use(passport.initialize());
app.use(passport.session());
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Omri Luzon
  • 3,975
  • 6
  • 20
  • 29

2 Answers2

1

The express-jwt library is initializing req.user based on the contents of the token that was included in the request.

If you require information at the req.user level you'll either need to include that information directly on the token or do an enrichment of req.user before running the role checks. For example, you could enrich req.user by running additional code that gets the roles based on the sub claim (user identifier).

João Angelo
  • 56,552
  • 12
  • 145
  • 147
0

The solution was to add the following code the auth0-lock configuration:

auth: {
    params: {
        scope: 'openid app_metadata roles'
    }
}

Which added the app_metadata and the roles array to req.user after decoding the token.

Omri Luzon
  • 3,975
  • 6
  • 20
  • 29