0

I have a nodejs express service with express-jwt with a protected api call.

app.get('/protected',
  jwtCheck, function(req, res) {
    console.log(JSON.stringify(req.user));
    if (!req.user.admin)
      return res.send("user");
    res.send("admin");
});

The problem is, the req.user object does not contain the "admin" field. I have added the roles in Auth0 rules, so I can get it to work in my client, just not in the nodejs server.

I followed the tutorial from here: https://github.com/auth0/express-jwt

Have I missed something here? Is there a rule I need to set in auth0 so the admin field is added?

EDIT: Found this description in a git issue: "Your token needs to contain the information (eg: roles). In order to do so with Auth0, you have to request the appropriate scope, eg: scope=openid email roles." Now, how do I edit the scope for express-jwt?

Thanks in advance!

  • In order to better understand the problem can you include a sample access token that you are using to call that API? It can be an expired token or you can [remove the signature part](https://auth0.com/learn/json-web-tokens/); additionally, if there is sensitive information on the payload you can mask the values (use [jwt.io](https://jwt.io/)). – João Angelo Oct 31 '16 at 12:27

1 Answers1

1

Does your req.user contain any data?

In the description it says:

"Middleware that validates JsonWebTokens and sets req.user."

That means when you do a request to the server with a vaild jwt-token in the Authorization header, the "express-jwt" lib will decode that token and store its payload to "req.user" for the following middlewares to take use of. Ie: this token:

"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50aWQiOiIxIiwiaWQiOiIyMzQ0IiwidXNlcm5hbWUiOiInTWFjRyciLCJpYXQiOjE0NzgyNTI1MzIsImV4cCI6MTQ3ODI1NDUzMn0.T_vPE8_Y2JQF9Xq9L2jOdcDoZC7rdDJioFb0DaDe9Zk"

That decodes to:

{
  "accountid": "1",
  "id": "2344",
  "username": "'MacG'",
  "iat": 1478252532,
  "exp": 1478254532
}

Will result in

req.user = {
  "accountid": "1",
  "id": "2344",
  "username": "'MacG'",
  "iat": 1478252532,
  "exp": 1478254532
}

SO, if you don't have a admin parameter in your token data, req.user.admin will be undefined. That is to say, "admin" in the code snippet you are referring to is just a kind of misleading example of how you could protect a route IF your token data contains the parameter "admin"

If your req.user doesn't contain any data at all you are probably hooking up your middelware functions in the wrong order. For that you will have to post more code to debug.

Out of Orbit
  • 543
  • 2
  • 5
  • 17