-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauthenticate.ts
168 lines (147 loc) · 6.23 KB
/
authenticate.ts
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import * as chardet from "chardet";
import { NextFunction, Request, Response } from "express";
import { readdir, readFile } from "fs/promises";
import * as iconv from "iconv-lite";
import { Trace } from "jinaga";
import { decode, JwtPayload, verify } from "jsonwebtoken";
import { join } from "path";
interface AuthenticationConfiguration {
provider: string;
issuer: string;
audience: string;
keyId: string;
key: string;
}
export function authenticate(configs: AuthenticationConfiguration[], allowAnonymous: boolean) {
return (req: Request, res: Response, next: NextFunction) => {
let possibleConfigs: AuthenticationConfiguration[] = configs;
try {
const authorization = req.headers.authorization;
if (authorization) {
const match = authorization.match(/^Bearer (.*)$/);
if (match) {
const token = match[1];
const payload = decode(token);
if (!payload || typeof payload !== "object") {
res.status(401).send("Invalid token");
return;
}
// Validate the subject.
const subject = payload.sub;
if (typeof subject !== "string") {
res.status(401).send("Invalid subject");
return;
}
// Validate the issuer and audience.
const issuer = payload.iss;
possibleConfigs = configs.filter(config => config.issuer === issuer);
if (possibleConfigs.length === 0) {
res.status(401).send("Invalid issuer");
return;
}
const audience = payload.aud;
possibleConfigs = possibleConfigs.filter(config => config.audience === audience);
if (possibleConfigs.length === 0) {
res.status(401).send("Invalid audience");
return;
}
let verified: string | JwtPayload | undefined;
let provider: string = "";
verify(token, (header, callback) => {
const config = possibleConfigs.find(config => config.keyId === header.kid);
if (!config) {
callback(new Error("Invalid key ID"));
return;
}
provider = config.provider;
callback(null, config.key);
}, (error, payload) => {
if (!error) {
verified = payload;
}
});
if (!verified) {
res.status(401).send("Invalid signature");
return;
}
// Pass the user record to the next handler.
const targetReq = <any>req;
targetReq.user = {
id: subject,
provider: provider,
profile: {
displayName: payload.display_name ?? ""
}
}
}
}
else if (!allowAnonymous) {
res.status(401).send("No token");
return;
}
next();
} catch (error) {
next(error);
}
}
}
export async function loadAuthenticationConfigurations(path: string): Promise<{ configs: AuthenticationConfiguration[], allowAnonymous: boolean }> {
const { providerFiles, hasAllowAnonymousFile } = await findProviderFiles(path);
if (!hasAllowAnonymousFile && providerFiles.length === 0) {
throw new Error(`No authentication configurations found in ${path}.`);
}
const configs: AuthenticationConfiguration[] = [];
for (const fileName of providerFiles) {
const config = await loadConfigurationFromFile(fileName);
configs.push(config);
}
if (hasAllowAnonymousFile) {
Trace.warn(`--------- Anonymous access is allowed!!! --------`);
}
return { configs, allowAnonymous: hasAllowAnonymousFile };
}
async function findProviderFiles(dir: string): Promise<{ providerFiles: string[], hasAllowAnonymousFile: boolean }> {
const providerFiles: string[] = [];
let hasAllowAnonymousFile = false;
const entries = await readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(dir, entry.name);
if (entry.isDirectory()) {
const result = await findProviderFiles(fullPath);
providerFiles.push(...result.providerFiles);
hasAllowAnonymousFile = hasAllowAnonymousFile || result.hasAllowAnonymousFile;
} else if (entry.isFile()) {
if (entry.name.endsWith('.provider')) {
providerFiles.push(fullPath);
} else if (entry.name === "allow-anonymous") {
hasAllowAnonymousFile = true;
}
}
}
return { providerFiles, hasAllowAnonymousFile };
}
async function loadConfigurationFromFile(path: string): Promise<AuthenticationConfiguration> {
try {
Trace.info(`Searching for authentication files in ${path}`);
const buffer = await readFile(path);
const encoding = chardet.detect(buffer) || 'utf-8';
const content = iconv.decode(buffer, encoding);
const config = JSON.parse(content);
if (!config.provider || !config.issuer || !config.audience || !config.key_id || !config.key) {
throw new Error(`Invalid authentication configuration`);
}
return {
provider: config.provider,
issuer: config.issuer,
audience: config.audience,
keyId: config.key_id,
key: config.key
};
} catch (error) {
if (error instanceof Error) {
throw new Error(`Error loading configuration from ${path}: ${error.message}`);
} else {
throw new Error(`Error loading configuration from ${path}: ${String(error)}`);
}
}
}