-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
57 lines (45 loc) · 1.56 KB
/
middleware.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
// an example nextJS middleware router that does server-side validation on all traffic to secure pages
import { NextResponse } from "next/server";
import { verifyTideCloakToken } from '/lib/tideJWT';
// Developer should list all secure pages and their respective allowed roles
const routesRoles = [
{ URLStart: "/adminprotected", role: 'appAdmin' },
{ URLStart: "/alsoprotected", role: 'offline_access' },
{ URLStart: "/protected", role: 'offline_access' },
];
export async function middleware(req) {
const { pathname } = req.nextUrl;
var requiredRole = null;
for (const { URLStart, role } of routesRoles) {
if (pathname.startsWith(URLStart)) {
requiredRole = role;
console.debug("[Middleware] Found role " + requiredRole);
break;
}
}
// Only protect routes starting with /protected
if (requiredRole == null) {
console.debug("[Middleware] skip next");
return NextResponse.next();
}
try {
// Extract token from cookie "kcToken"
const token = req.cookies?.get('kcToken')?.value;
if (!token) {
console.debug("[Middleware] No token found -> redirecting to /");
return NextResponse.redirect(new URL("/", req.url));
}
const user = await verifyTideCloakToken(token, requiredRole);
if (user) {
return NextResponse.next();
}
throw "Token verification failed.";
} catch (err) {
console.error("[Middleware] ", err);
return NextResponse.redirect(new URL("/fail", req.url));
}
}
//Which routes the middleware should run on:
export const config = {
matcher: ["/protected/:path*"],
};