Node.js - Express.js JWT always returns an invalid token error in browser response

前端 未结 2 1047
难免孤独
难免孤独 2021-01-17 12:28

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:

<         


        
相关标签:
2条回答
  • 2021-01-17 13:06

    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);
      });
    
    0 讨论(0)
  • 2021-01-17 13: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

    0 讨论(0)
提交回复
热议问题