Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJs - Retrieve user infor from JWT token?

Tags:

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. Assigning the JWT token to config.headers through service interceptor:

var token = jwt.sign({id: user._id}, secret.secretToken, { expiresIn: tokenManager.TOKEN_EXPIRATION_SEC });             return res.json({token:token}); 

authservice.js Interceptor(omitted requestError,response and responseError):

authServices.factory('TokenInterceptor', ['$q', '$window', '$location','AuthenticationService',function ($q, $window, $location, AuthenticationService) {         return {             request: function (config) {                 config.headers = config.headers || {};                 if ($window.sessionStorage.token) {                     config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;                 }                 return config;             }                        };     }]); 

Now I wanted to get the logged in user details from the token, How can I do that? I tried as follows, not working. When I log the error from Users.js file it's saying "ReferenceError: headers is not defined"

authController.js:

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

authService.js:

authServices.factory('UserService',['$http', function($http) {   return {             me:function() {     return $http.get(options.api.base_url + '/me');     }   } }]); 

Users.js (Node):

 exports.me = function(req,res){     if (req.headers && req.headers.authorization) {         var authorization =req.headers.authorization;         var part = authorization.split(' ');         //logic here to retrieve the user from database     }     return res.send(200); } 

Do i have to pass the token as a parameter too for retrieving the user details? Or save the user details in a separate session variable as well?

like image 310
hakuna Avatar asked Oct 31 '15 12:10

hakuna


People also ask

Can we get username from JWT token?

username key value pair inside the jwt. sign function, _username is the key and this. username should be your actual username which is in the database. please find the code section where you create the jwt token from the server side.in there you can pass username as a input data to sign the jwt.


2 Answers

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); } 
like image 165
Constantine Poltyrev Avatar answered Oct 05 '22 11:10

Constantine Poltyrev


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); 
like image 20
Ajay yadav Avatar answered Oct 05 '22 11:10

Ajay yadav