Express Server with Auth0 and JWT
const express = require('express');
// Give access to env variables in this file
require('dotenv').config();
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');
const checkScope = require('express-jwt-authz');
const checkJwt = jwt({
// Provide a Signing key
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${
process.env.REACT_APP_AUTH0_DOMAIN
}/.well-known/jwks.json`
}),
// Validate audience and the issuer.
audience: process.env.REACT_APP_AUTH0_AUDIENCE,
issuer: `https://${process.env.REACT_APP_AUTH0_DOMAIN}/`,
// Algorithm selected in Auth0
algorithms: ['RS256']
});
// CREATES EXPRESS APP
const app = express();
app.get('/public', function(req, res) {
res.json({
message: "Hello from a public API!"
});
});
app.get('/private', checkJwt, function(req, res) {
res.json({
message: "Hello from a private API!"
});
});
app.get('/courses', checkJwt, checkScope(["read:courses"]), function(req, res) {
res.json({
courses: [
{ id: 1, title: "algo" },
{ id: 2, title: "algo 2" }
]
});
});
function checkRole(role) {
return function (req, res, next) {
const assignedRoles = req.user["http://localhost:3000/roles"];
if (Array.isArray(assignedRoles) && assignedRoles.includes(role)) {
return next();
} else {
return res.status(401).send("Insufficient Role");
}
};
}
app.get('/admin', checkJwt, checkRole('admin'), function(req, res) {
res.json({
message: "Hello from an admin API!"
});
});
app.listen(3001);
console.log("API server listening on: " + process.env.REACT_APP_AUTH0_AUDIENCE);