Created
February 1, 2018 13:41
-
-
Save Spyna/2014de9d0447576b647f42e7ccc03ecd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var jwt = require('./jwt'); | |
const checkToken = ( req ) => { | |
//get the http header 'authorization' | |
let authorization = req.get( 'authorization' ); | |
if ( !authorization ) { | |
throw new Error( 401 ) | |
} | |
//check the token signature with 'jwt.js' library | |
let token = authorization.replace( 'Bearer ', '' ); | |
return jwt.verify( token ); | |
} | |
const authMiddleware = ( req, res, next ) => { | |
try { | |
let shouldProtect = getProtectedResource( req, this.config.routes ); | |
//add a configuration to protect some resources | |
if ( shouldProtect ) { | |
//if the url is protected we must check the token | |
let principal = checkToken( req ); | |
res.locals.principal = principal; | |
} | |
next(); | |
} catch ( e ) { | |
//if any error coccurs, we do not authorize the request | |
console.log( "unouthorized", e ) | |
res | |
.status( 401 ) | |
.end( JSON.stringify( { error: "not_authorized" } ) ); | |
} | |
} | |
var app = express(); | |
//tell express to use the middleware | |
app.use( authMiddleware ) | |
app.get( '/protected', ( req, res ) => { | |
let principal = res.locals.principal; | |
console.log( principal ) | |
let localUser = userStore.get( principal.sub ); | |
console.log( localUser ) | |
let name = localUser ? localUser.name : principal.sub; | |
res.setHeader( 'Content-Type', 'application/json' ); | |
res.send( JSON.stringify( { | |
user: name | |
} ) ); | |
} ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment