Skip to content

Instantly share code, notes, and snippets.

@bioball
Last active August 29, 2015 14:01
Show Gist options
  • Save bioball/403d50d259c79f7e8a89 to your computer and use it in GitHub Desktop.
Save bioball/403d50d259c79f7e8a89 to your computer and use it in GitHub Desktop.
JWT verification middleware example
// This is an example express middleware that can be inserted into any route that needs to be protected, assuming that authentication is done via JSON web tokens
var crypto = require('crypto');
var verifyJWTToken = function(req, res, next){
var secret = process.env.TOKEN_SECRET;
// 1. get the token from the headers. I'm going to go ahead and split up the three parts already
var token = req.headers['x-access-token'].split('.');
// 2. Get the signature, and the rest of the token. Calculate the digest with HMAC-SHA256 so we can see if it matches the signature
var signature = token[2];
var restOfToken = token[0] + '.' + token[1];
var digest = crypto.createHmac('SHA256', secret).update(restOfToken).digest('hex');
// 3. Get the expiration time
var body = JSON.parse(new Buffer(token[1], 'base64').toString());
var timeUntilExpiry = body.exp - Date.now();
// If the signature matches our digest, and the token hasn't expired yet, let the user through. Otherwise send a 401
if (digest === signature && timeUntilExpiry > 0 {
next();
} else {
res.send(401);
}
};
// This is assuming
// 1. There is a token that is being sent under the header with this syntax: "x-access-token: [token]"
// 2. There is an environment variable called "TOKEN_SECRET" that is a string
// 3. That we want to use HMAC-SHA256 to calcaulate the digest and sign the token
// 4. That the expiration time is included in the body as "exp", and is in JS format of number of milliseconds since Jan 1, 1970
// 5. The token that was originally created was signed with the same secret as what's stored in TOKEN_SECRET
// So in an actual express app, this is how you'd use the middleware for protected routes
app.post('/order', verifyJWTToken, function(req, res){
// business logic
});
// Note that this is just logic to verify the session, not to authenticate the user in the first place.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment