Skip to content

Commit a171f97

Browse files
committed
Add example with express js
1 parent abdb3d7 commit a171f97

File tree

4 files changed

+1190
-0
lines changed

4 files changed

+1190
-0
lines changed

with-express-js/auth_middleware.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
const { Authorizer } = require("@authorizerdev/authorizer-js");
2+
3+
const authRef = new Authorizer({
4+
authorizerURL: "https://demo.authorizer.dev",
5+
redirectURL: "https://demo.authorizer.dev/app",
6+
clientID: "96fed66c-9779-4694-a79a-260fc489ce33",
7+
});
8+
9+
const authMiddleware = async (req, res, next) => {
10+
const authHeader = req.headers.authorization;
11+
if (!authHeader) {
12+
return res.status(403).json({ error: "Authorization not found" });
13+
}
14+
15+
const splitHeader = authHeader.split(" ");
16+
if (splitHeader.length != 2) {
17+
return res.status(403).json({ error: "Invalid auth header" });
18+
}
19+
20+
if (splitHeader[0].toLowerCase() != "bearer") {
21+
return res.status(403).json({ error: "Bearer token not found" });
22+
}
23+
24+
const token = splitHeader[1];
25+
// Validate jwt token via authorizer sdk
26+
try {
27+
const res = await authRef.validateJWTToken({
28+
token,
29+
token_type: "id_token", // This can be access_token, refresh_token
30+
// roles: [user] // specify roles that you want to validate jwt for, by default it will just verify jwt.
31+
});
32+
req.user = res.claims;
33+
} catch (err) {
34+
console.error(err);
35+
return res.status(403).json({ error: "Invalid JWT token" });
36+
}
37+
38+
next();
39+
};
40+
41+
module.exports = authMiddleware;

with-express-js/index.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const express = require("express");
2+
const authMiddleware = require("./auth_middleware");
3+
4+
const app = express();
5+
const port = `3000`;
6+
7+
app.get("/", authMiddleware, (req, res) => {
8+
res.send("Hello World");
9+
});
10+
11+
app.listen(port, () => {
12+
console.log(`[server]: Server is running at http://localhost:${port}`);
13+
});

0 commit comments

Comments
 (0)