-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthorization-server.js
89 lines (80 loc) · 2.24 KB
/
authorization-server.js
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
Simple authorization server to practice secure coding in JavaScript
PGCM - (c) 2025 - GPLv3
**/
import express from "express"
import cors from "cors"
import bodyParser from "body-parser"
import Cerbos from "@cerbos/http"
import jwt from "jsonwebtoken"
import https from "https"
import {
authzPort,
authzUrl,
httpsOptions,
jwtSecret,
webUrl,
cerbosUrl,
} from "./settings.js"
// For demonstration purposes, use a fixed resource identifier
const resourceId = "31337"
const app = express()
// Hardening: Remove vanity header for all requests
app.use((req, res, next) => {
res.removeHeader("x-powered-by")
next()
})
// Only allow a predefined origin
let corsOptions = { origin: webUrl }
app.use(cors(corsOptions))
app.use(bodyParser.json())
// Initialize Cerbos client
const cerbos = new Cerbos.HTTP(cerbosUrl)
// Handle authorization
app.post("/authorize", async (req, res) => {
const { token, action } = req.body
if (token && action) {
try {
// First, authenticate
const decoded = jwt.verify(token, jwtSecret)
console.log(
`Token validated for ${decoded.username}, having role ${decoded.role}`,
)
// Then, authorize
const decision = await cerbos.checkResource({
principal: {
id: decoded.username,
roles: [decoded.role],
},
resource: {
kind: "assets",
id: resourceId,
},
actions: [action],
})
res.json({ isAllowed: decision.isAllowed(action) })
} catch (error) {
console.error("Authorization error:", error)
res.status(401).json({ error: "Authorization failed" })
}
} else {
res.status(401).json({ error: "Authorization failed" })
}
})
// Gracefully deal with standard GET requests
app.get("/", (req, res) => {
res.send("Authorization server up and running")
})
function ensureEnvVars(...vars) {
vars.forEach((key) => {
if (!process.env[key]) {
console.error(`${key} is not set in the environment variables`)
process.exit(1)
}
})
}
// Start the server
const server = https.createServer(httpsOptions, app).listen(authzPort, () => {
console.log(`Authorization server running at https://${authzUrl}`)
console.log(`Using ${cerbosUrl} as authorization back-end`)
})