12

I'm using node.js and express.js with the express-jwt module, and I have set up a simple HTTP server to test everything:

This is the node code involved:

 app.set('port', process.env.PORT || 3000);
    app.use(express.methodOverride());
    app.use(allow_cross_domain);
    app.use('/api', expressJwt({secret: '09qrjjwef923jnrge$5ndjwk'}));
    app.use(express.json());
    app.use(express.urlencoded());
    app.use('/', express.static(__dirname + '/'));
    app.use(function(err, req, res, next){
      if (err.constructor.name === 'UnauthorizedError') {
        res.send(401, 'Unauthorized');
      }
    });

    app.get('login',function(req,res){

    //...
    jwt.sign(results.username+results.email, secret, { expiresInMinutes: 9000000000*9393939393393939393939 });
    });

    app.post('api/profile',function(req,res){
     console.log(req.user); // this return undefined in console
     res.send(req.user); // response is pending and dunno why it returns error in browser console
    });

So once I open the /login URL I get logged in and I send the session token to api/post, which returns this response error in the browser console:

{"error":{"message":"invalid signature","code":"invalid_token","status":401,"inner":{}}}

I don't understand why this is happening, because the token stored in the front-end and the token in JWT are the same. What could be the reason for this error?

An example of headers POSTed to the api/post URL:

enter image description here

mustaccio
  • 18,234
  • 16
  • 48
  • 57
itsme
  • 48,972
  • 96
  • 224
  • 345
  • can you show the value of "secret" in jwt.sign? Also, results.username + results.email is a JSON? jwt.sign takes a json object. – woloski Feb 19 '14 at 15:24
  • @woloski thanks man for replying me, i do not set a value to secret var in sign() since i thought using the **app.use('/api', expressJwt({secret: '09qrjjwef923jnrge$5ndjwk'}));** was already setted :P i'm mistaking? – itsme Feb 19 '14 at 15:30
  • @woloski the user is not a json actually i need to set it as json yeah i'll try it ! thankss – itsme Feb 19 '14 at 15:34
  • @woloski tryed using something like **jwt.sign(JSON.stringify("{ops:asd}"), secret, etc...** but it won't work :( it gets 401 but no more invalid token error message actually – itsme Feb 19 '14 at 15:38
  • @woloski IT WORKS NOW!! man you my idol, it was that i wasn't passing a JSON into sign() now everythings ok!!! thank you, just curious... where do sign() stores the tokens? – itsme Feb 19 '14 at 15:45

2 Answers2

13

Here is an example

http://blog.auth0.com/2014/01/07/angularjs-authentication-with-cookies-vs-token/

var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');

var SECRET = 'shhhhhhared-secret';

app.use('/api', expressJwt({secret: SECRET}));

app.post('/authenticate', function (req, res) {
  //TODO validate req.body.username and req.body.password
  //if is invalid, return 401
  if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) {
    res.send(401, 'Wrong user or password');
    return;
  }

  var profile = {
    first_name: 'John',
    last_name: 'Doe',
    email: 'john@doe.com',
    id: 123
  };

  // We are sending the profile inside the token
  var token = jwt.sign(profile, SECRET, { expiresIn: 18000 }); // 60*5 minutes

  res.json({ token: token });
});

app.get('/api/protected', 
  function(req, res) {  
    res.json(req.user);
  });
Nishant Ghodke
  • 923
  • 1
  • 12
  • 21
woloski
  • 2,863
  • 16
  • 14
  • just if i may ask ... is it safe to put user's email in the token? – itsme Feb 19 '14 at 15:58
  • sorry man, i got a question more if you can please, when i sign a new token for the same user and i'm signing they with no Expiration, where do the old token and how the old token gets deleted? i mean how do i remove old tokens when creating new? thank you again – itsme Feb 20 '14 at 09:22
  • i've opened a new question you might be interested in ;) http://stackoverflow.com/questions/21904382/node-js-jwt-token-and-logic-behind – itsme Feb 20 '14 at 10:07
10

Also, make sure you don't put a : after bearer. E.g.

BAD! Authorization: Bearer: eyJ0eXAiOiI1NiJ9.eyJpZCMjEyNzk2Njl9.4eU6X1wAQieH Prints "UnauthorizedError: jwt must be provided" to logs

Good Authorization: Bearer eyJ0eXAiOiI1NiJ9.eyJpZCMjEyNzk2Njl9.4eU6X1wAQieH

Michael Cole
  • 15,473
  • 7
  • 79
  • 96