Skip to content

Instantly share code, notes, and snippets.

@ggoodman
Last active March 5, 2018 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggoodman/d80a28216798d7ac0e9bb7f5601b0387 to your computer and use it in GitHub Desktop.
Save ggoodman/d80a28216798d7ac0e9bb7f5601b0387 to your computer and use it in GitHub Desktop.
'use strict';
const Assert = require('assert');
Assert.ok(module.webtask.secrets['jwt-scope'], 'The jwt-scope secret is required for the jwt-authz');
module.exports = () => {
const requiredScopes = module.webtask.secrets['jwt-scope'].split(/\s+/);
return function middleware(req, res, next) {
if (!req.user) {
const error = new Error('Unauthenticated request');
error.statusCode = 403;
return next(error);
}
const authenticatedScopes = (req.user.scope || '').split(/\s+/);
const hasScope = requiredScope => authenticatedScopes.indexOf(requiredScope) !== -1;
if (!authenticatedScopes.every(hasScope)) {
const error = new Error(`Unauthorized: Missing required scopes '${requiredScopes.join(' ')}'`);
error.statusCode = 401;
return next(error);
}
return next();
};
};
'use strict';
const Assert = require('assert');
const ExpressJwt = require('express-jwt');
const JwksRsa = require('jwks-rsa');
Assert.ok(module.webtask.secrets['jwt-audience'], 'The jwt-audience secret is required for the jwt-middleware');
Assert.ok(module.webtask.secrets['jwt-issuer'], 'The jwt-issuer secret is required for the jwt-middleware');
module.exports = () => {
const jwtAudience = module.webtask.secrets['jwt-audience'];
const jwtIssuer = module.webtask.secrets['jwt-issuer'];
const loadRsaKey = JwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `${jwtIssuer}.well-known/jwks.json`,
});
const middleware = ExpressJwt({
algorithms: ['RS256'],
audience: jwtAudience,
issuer: jwtIssuer,
secret: loadRsaKey,
});
return middleware;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment