NodeJs - Retrieve user infor from JWT token?

前端 未结 4 540
天涯浪人
天涯浪人 2020-12-06 00:19

Node and Angular. I have a MEAN stack authentication application where I am setting a JWT token on successful login as follows, and storing it in a session in the controller

相关标签:
4条回答
  • 2020-12-06 00:24

    Your are calling the function UserService.me with two callbacks, although the function does not accept any arguments. What I think you want to do is:

    $scope.me = function() {
        UserService.me().then(function(res) {
          $scope.myDetails = res;
        }, function() {
          console.log('Failed to fetch details');
          $rootScope.error = 'Failed to fetch details';
        });
      };
    

    Also, note that the $http methods return a response object. Make sure that what you want is not a $scope.myDetails = res.data

    And in your Users.js file, you are using the variable headers.authorization directly, whereas it should be req.header.authorization:

    var authorization = req.headers.authorization;
    
    0 讨论(0)
  • 2020-12-06 00:34

    According to the documentation https://github.com/themikenicholson/passport-jwt, you could use request.user. Note, I'm supposing that you are using passport with passport-jwt. It's possible because passport during the context of an authentication is setting the request object and populating the user property. So, just access that property. You don't need to do a middleware.

    0 讨论(0)
  • 2020-12-06 00:37

    Find a token from request data:

    const usertoken = req.headers.authorization;
    const token = usertoken.split(' ');
    const decoded = jwt.verify(token[1], 'secret-key');
    console.log(decoded);
    
    0 讨论(0)
  • 2020-12-06 00:46

    First of all, it is a good practice to use Passport middleware for user authorization handling. It takes all the dirty job of parsing your request and also provides many authorization options. Now for your Node.js code. You need to verify and parse the passed token with jwt methods and then find the user by id extracted from the token:

    exports.me = function(req,res){
        if (req.headers && req.headers.authorization) {
            var authorization = req.headers.authorization.split(' ')[1],
                decoded;
            try {
                decoded = jwt.verify(authorization, secret.secretToken);
            } catch (e) {
                return res.status(401).send('unauthorized');
            }
            var userId = decoded.id;
            // Fetch the user by id 
            User.findOne({_id: userId}).then(function(user){
                // Do something with the user
                return res.send(200);
            });
        }
        return res.send(500);
    }
    
    0 讨论(0)
提交回复
热议问题