Node JS with express-jwt example

JWT package

  • express-jwt
  • jsonwebtoken
Step 1,

Client side sends the login request to server with ID and password.

Step 2,

If server side verified ID and password successfully, it will return the signed jwt token to client, and also store the jwt token to Redis or DB for further verification.

var jwt = require('jsonwebtoken');  
var secretToken = 'aMdoeb5ed87zorRdkD6greDML81DcnrzeSD648ferFejmplx';  
var token = jwt.sign({id: user._id}, secretToken, { expiresInMinutes: tokenManager.TOKEN_EXPIRATION });  
return res.json({token:token});  
Step 3,

When Client Side gets the login response with token, it should store the jwt token to client side(localStorage) and send the token for every future request, Suggest to use client side interceptor to do the job.
AngularJS Example,

appServices.factory('TokenInterceptor', 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;
        }
}

app.config(function ($httpProvider) {  
    $httpProvider.interceptors.push('TokenInterceptor');
});
Step 4,

For every request which needs be authorized, we add jwt (express-jwt) middleware for the request, jwt middleware will put decoded token in req.user for each request if the token is verified(can be decoded by secret), then we can verify the value in the req.user to see if it matches the token we generated/stored in step 1.

var jwt = require('express-jwt');  
app.get('/post/create', jwt({secret:secretToken}), routes.users.care);