-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
67 lines (56 loc) · 2.03 KB
/
Copy pathserver.js
File metadata and controls
67 lines (56 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const express = require("express");
require("dotenv").config();
const jwt = require("express-jwt"); // Validate JWT and set req.user
const jwksRsa = require("jwks-rsa"); // Retrieve RSA keys from a JSON Web Key set (JWKS) endpoint
const checkScope = require("express-jwt-authz"); // Validate JWT scopes
const checkJwt = jwt({
// Dynamically provide a signing key based on the kid in the header
// and the signing keys provided by the JWKS endpoint.
secret: jwksRsa.expressJwtSecret({
cache: true, // cache the signing key
rateLimit: true,
jwksRequestsPerMinute: 5, // prevent attackers from requesting more than 5 per minute
jwksUri: `https://${process.env.REACT_APP_AUTH0_DOMAIN}/.well-known/jwks.json`,
}),
// Validate the audience and the issuer.
audience: process.env.REACT_APP_AUTH0_AUDIENCE,
issuer: `https://${process.env.REACT_APP_AUTH0_DOMAIN}/`,
// This must match the algorithm selected in the Auth0 dashboard under your app's advanced settings under the OAuth tab
algorithms: ["RS256"],
});
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("/course", checkJwt, checkScope(["read:courses"]), function (req, res) {
res.json({
courses: [
{ id: 1, title: "Building Apps with React and Redux" },
{ id: 2, title: "Creating Reusable React Components" },
],
});
});
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_API_URL);