-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathauthentication.ts
More file actions
84 lines (66 loc) · 2.05 KB
/
authentication.ts
File metadata and controls
84 lines (66 loc) · 2.05 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { auth, requiredScopes } from "express-oauth2-jwt-bearer";
import { getConfig } from "./config";
import type { Request, Response, Express, NextFunction } from "express";
import { get, set } from "./services/storageClient/redis";
export const tokenCookieName = "authorizationToken";
export const tokenAuthenticationMiddleware = async (
req: Request,
res: Response,
next: NextFunction,
) => {
const token = req.query?.token as string;
if (token) {
const redisKey = `token-${token}`;
const { authorizationJwt, ...widgetParams } = (await get(redisKey)) || {};
if (!authorizationJwt) {
res.send("token invalid or expired");
res.status(401);
return;
}
await set(redisKey, widgetParams);
const config = getConfig();
req.headers.authorization = `Bearer ${authorizationJwt}`;
res.cookie(tokenCookieName, authorizationJwt, {
httpOnly: true,
sameSite: config.AUTHORIZATION_TOKEN_COOKIE_SAMESITE || "strict",
secure: true,
});
}
next();
};
export const cookieAuthenticationMiddleware = (
req: Request,
_res: Response,
next: NextFunction,
) => {
const cookieAuthorizationToken = req.cookies[tokenCookieName];
if (cookieAuthorizationToken && !req.headers.authorization) {
req.headers.authorization = `Bearer ${cookieAuthorizationToken}`;
}
next();
};
const useAuthentication = (app: Express) => {
const config = getConfig();
if (config.AUTHENTICATION_ENABLE !== "true") {
return;
}
app.use(tokenAuthenticationMiddleware);
app.use(cookieAuthenticationMiddleware);
if (
config.AUTHENTICATION_AUDIENCE &&
config.AUTHENTICATION_ISSUER_BASE_URL &&
config.AUTHENTICATION_TOKEN_SIGNING_ALG
) {
app.use(
auth({
audience: config.AUTHENTICATION_AUDIENCE,
issuerBaseURL: config.AUTHENTICATION_ISSUER_BASE_URL,
tokenSigningAlg: config.AUTHENTICATION_TOKEN_SIGNING_ALG,
}),
);
}
if (config.AUTHENTICATION_SCOPES) {
app.use(requiredScopes(config.AUTHENTICATION_SCOPES));
}
};
export default useAuthentication;