-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
oauth2.ts
323 lines (269 loc) · 9.08 KB
/
oauth2.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import { Router } from 'express';
import { Issuer, Client, generators, errors } from 'openid-client';
import jwt from 'jsonwebtoken';
import ms from 'ms';
import { LocalAuthDriver } from './local';
import { getAuthProvider } from '../../auth';
import env from '../../env';
import { AuthenticationService, UsersService } from '../../services';
import { AuthDriverOptions, User, AuthData, SessionData } from '../../types';
import {
InvalidCredentialsException,
ServiceUnavailableException,
InvalidConfigException,
InvalidTokenException,
} from '../../exceptions';
import { respond } from '../../middleware/respond';
import asyncHandler from '../../utils/async-handler';
import { Url } from '../../utils/url';
import logger from '../../logger';
export class OAuth2AuthDriver extends LocalAuthDriver {
client: Client;
redirectUrl: string;
usersService: UsersService;
config: Record<string, any>;
constructor(options: AuthDriverOptions, config: Record<string, any>) {
super(options, config);
const { authorizeUrl, accessUrl, profileUrl, clientId, clientSecret, ...additionalConfig } = config;
if (!authorizeUrl || !accessUrl || !clientId || !clientSecret || !additionalConfig.provider) {
throw new InvalidConfigException('Invalid provider config', { provider: additionalConfig.provider });
}
const redirectUrl = new Url(env.PUBLIC_URL).addPath('auth', 'login', additionalConfig.provider, 'callback');
this.redirectUrl = redirectUrl.toString();
this.usersService = new UsersService({ knex: this.knex, schema: this.schema });
this.config = additionalConfig;
const issuer = new Issuer({
authorization_endpoint: authorizeUrl,
token_endpoint: accessUrl,
userinfo_endpoint: profileUrl,
// Required for openid providers (openid flow should be preferred!)
issuer: additionalConfig.issuerUrl,
});
this.client = new issuer.Client({
client_id: clientId,
client_secret: clientSecret,
redirect_uris: [this.redirectUrl],
response_types: ['code'],
});
}
generateCodeVerifier(): string {
return generators.codeVerifier();
}
generateAuthUrl(codeVerifier: string, prompt = false): string {
try {
const codeChallenge = generators.codeChallenge(codeVerifier);
const paramsConfig = typeof this.config.params === 'object' ? this.config.params : {};
return this.client.authorizationUrl({
scope: this.config.scope ?? 'email',
access_type: 'offline',
prompt: prompt ? 'consent' : undefined,
...paramsConfig,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
// Some providers require state even with PKCE
state: codeChallenge,
});
} catch (e) {
throw handleError(e);
}
}
private async fetchUserId(identifier: string): Promise<string | undefined> {
const user = await this.knex
.select('id')
.from('directus_users')
.whereRaw('LOWER(??) = ?', ['external_identifier', identifier.toLowerCase()])
.first();
return user?.id;
}
async getUserID(payload: Record<string, any>): Promise<string> {
if (!payload.code || !payload.codeVerifier) {
throw new InvalidCredentialsException();
}
let tokenSet;
let userInfo;
try {
tokenSet = await this.client.oauthCallback(
this.redirectUrl,
{ code: payload.code, state: payload.state },
{ code_verifier: payload.codeVerifier, state: generators.codeChallenge(payload.codeVerifier) }
);
const issuer = this.client.issuer;
if (issuer.metadata.userinfo_endpoint) {
userInfo = await this.client.userinfo(tokenSet.access_token!);
} else if (tokenSet.id_token) {
userInfo = tokenSet.claims();
} else {
throw new InvalidConfigException('OAuth profile URL not defined', { provider: this.config.provider });
}
} catch (e) {
throw handleError(e);
}
const { emailKey, identifierKey, allowPublicRegistration } = this.config;
const email = userInfo[emailKey ?? 'email'] as string | null | undefined;
// Fallback to email if explicit identifier not found
const identifier = (userInfo[identifierKey] as string | null | undefined) ?? email;
if (!identifier) {
logger.warn(`Failed to find user identifier for provider "${this.config.provider}"`);
throw new InvalidCredentialsException();
}
const userId = await this.fetchUserId(identifier);
if (userId) {
// Update user refreshToken if provided
if (tokenSet.refresh_token) {
await this.usersService.updateOne(userId, {
auth_data: JSON.stringify({ refreshToken: tokenSet.refresh_token }),
});
}
return userId;
}
// Is public registration allowed?
if (!allowPublicRegistration) {
throw new InvalidCredentialsException();
}
await this.usersService.createOne({
provider: this.config.provider,
email: email,
external_identifier: identifier,
role: this.config.defaultRoleId,
auth_data: tokenSet.refresh_token && JSON.stringify({ refreshToken: tokenSet.refresh_token }),
});
return (await this.fetchUserId(identifier)) as string;
}
async login(user: User): Promise<SessionData> {
return this.refresh(user, null);
}
async refresh(user: User, sessionData: SessionData): Promise<SessionData> {
let authData = user.auth_data as AuthData;
if (typeof authData === 'string') {
try {
authData = JSON.parse(authData);
} catch {
logger.warn(`Session data isn't valid JSON: ${authData}`);
}
}
if (authData?.refreshToken) {
try {
const tokenSet = await this.client.refresh(authData.refreshToken);
// Update user refreshToken if provided
if (tokenSet.refresh_token) {
await this.usersService.updateOne(user.id, {
auth_data: JSON.stringify({ refreshToken: tokenSet.refresh_token }),
});
}
} catch (e) {
throw handleError(e);
}
}
return sessionData;
}
}
const handleError = (e: any) => {
if (e instanceof errors.OPError) {
if (e.error === 'invalid_grant') {
// Invalid token
return new InvalidTokenException();
}
// Server response error
return new ServiceUnavailableException('Service returned unexpected response', {
service: 'openid',
message: e.error_description,
});
} else if (e instanceof errors.RPError) {
// Internal client error
return new InvalidCredentialsException();
}
return e;
};
export function createOAuth2AuthRouter(providerName: string): Router {
const router = Router();
router.get(
'/',
(req, res) => {
const provider = getAuthProvider(providerName) as OAuth2AuthDriver;
const codeVerifier = provider.generateCodeVerifier();
const prompt = !!req.query.prompt;
const token = jwt.sign({ verifier: codeVerifier, redirect: req.query.redirect, prompt }, env.SECRET as string, {
expiresIn: '5m',
issuer: 'directus',
});
res.cookie(`oauth2.${providerName}`, token, {
httpOnly: true,
sameSite: 'lax',
});
return res.redirect(provider.generateAuthUrl(codeVerifier, prompt));
},
respond
);
router.get(
'/callback',
asyncHandler(async (req, res, next) => {
let tokenData;
try {
tokenData = jwt.verify(req.cookies[`oauth2.${providerName}`], env.SECRET as string, { issuer: 'directus' }) as {
verifier: string;
redirect?: string;
prompt: boolean;
};
} catch (e) {
logger.warn(`Couldn't verify OAuth2 cookie`);
throw new InvalidCredentialsException();
}
const { verifier, redirect, prompt } = tokenData;
const authenticationService = new AuthenticationService({
accountability: {
ip: req.ip,
userAgent: req.get('user-agent'),
role: null,
},
schema: req.schema,
});
let authResponse;
try {
res.clearCookie(`oauth2.${providerName}`);
if (!req.query.code || !req.query.state) {
logger.warn(`Couldn't extract OAuth2 code or state from query: ${JSON.stringify(req.query)}`);
}
authResponse = await authenticationService.login(providerName, {
code: req.query.code,
codeVerifier: verifier,
state: req.query.state,
});
} catch (error: any) {
// Prompt user for a new refresh_token if invalidated
if (error instanceof InvalidTokenException && !prompt) {
return res.redirect(`./?${redirect ? `redirect=${redirect}&` : ''}prompt=true`);
}
logger.warn(error);
if (redirect) {
let reason = 'UNKNOWN_EXCEPTION';
if (error instanceof ServiceUnavailableException) {
reason = 'SERVICE_UNAVAILABLE';
} else if (error instanceof InvalidCredentialsException) {
reason = 'INVALID_USER';
} else if (error instanceof InvalidTokenException) {
reason = 'INVALID_TOKEN';
}
return res.redirect(`${redirect.split('?')[0]}?reason=${reason}`);
}
throw error;
}
const { accessToken, refreshToken, expires } = authResponse;
if (redirect) {
res.cookie(env.REFRESH_TOKEN_COOKIE_NAME, refreshToken, {
httpOnly: true,
domain: env.REFRESH_TOKEN_COOKIE_DOMAIN,
maxAge: ms(env.REFRESH_TOKEN_TTL as string),
secure: env.REFRESH_TOKEN_COOKIE_SECURE ?? false,
sameSite: (env.REFRESH_TOKEN_COOKIE_SAME_SITE as 'lax' | 'strict' | 'none') || 'strict',
});
return res.redirect(redirect);
}
res.locals.payload = {
data: { access_token: accessToken, refresh_token: refreshToken, expires },
};
next();
}),
respond
);
return router;
}