AllenYuan

auth middleware

May 7th, 2020
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var jwt = require('express-jwt');
  2. var secret = require('../config').secret;
  3.  
  4. // utility to parse token from headers.authorization
  5. function getTokenFromHeader(req) {
  6.   if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Token') {
  7.     return req.headers.authorization.split(' ')[1];
  8.   }
  9.  
  10.   return null;
  11. }
  12.  
  13. // methods for routes where auth is required and optional
  14. var auth = {
  15.   // both these methods validate the token against the secret in config
  16.   required: jwt({
  17.     secret: secret,
  18.     userProperty: 'payload',
  19.     getToken: getTokenFromHeader
  20.   }),
  21.   optional: jwt({
  22.     secret: secret,
  23.     userProperty: 'payload',
  24.     credentialsRequired: false,
  25.     getToken: getTokenFromHeader
  26.   })
  27. };
  28.  
  29. module.exports = auth;
Advertisement
Add Comment
Please, Sign In to add comment