-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathauth.ts
334 lines (295 loc) · 9.73 KB
/
auth.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
324
325
326
327
328
329
330
331
332
333
334
import {IHttpClient} from "./httpClient";
interface IAuthenticatorResult {
accessToken: string
expiresAt: number
refreshToken: string
}
interface IAuthenticator {
refresh: () => Promise<IAuthenticatorResult>
}
export class Authenticator {
private readonly http: IHttpClient
private readonly creds: any
private accessToken: string
private refreshToken?: string;
private expiresAt: number;
private refreshRunning: boolean;
constructor(http: IHttpClient, creds: any) {
this.http = http;
this.creds = creds;
this.accessToken = "";
this.refreshToken = "";
this.expiresAt = 0
this.refreshRunning = false;
// If the authentication method is access token,
// our bearer token is already available for use
if (this.creds instanceof AuthAccessTokenCredentials) {
this.accessToken = this.creds.accessToken;
this.expiresAt = this.creds.expiresAt
this.refreshToken = this.creds.refreshToken;
}
}
refresh = async (localConfig: any) => {
let config = await this.getOpenidConfig(localConfig);
let authenticator: IAuthenticator;
switch (this.creds.constructor) {
case AuthUserPasswordCredentials:
authenticator = new UserPasswordAuthenticator(this.http, this.creds, config);
break;
case AuthAccessTokenCredentials:
authenticator = new AccessTokenAuthenticator(this.http, this.creds, config);
break;
case AuthClientCredentials:
authenticator = new ClientCredentialsAuthenticator(this.http, this.creds, config);
break;
default:
throw new Error("unsupported credential type");
}
return authenticator.refresh()
.then(resp => {
this.accessToken = resp.accessToken;
this.expiresAt = resp.expiresAt;
this.refreshToken = resp.refreshToken;
if (!this.refreshRunning && this.refreshTokenProvided()) {
this.runBackgroundTokenRefresh(authenticator);
this.refreshRunning = true;
}
});
};
getOpenidConfig = async (localConfig: any) => {
return this.http.externalGet(localConfig.href)
.then((openidProviderConfig: any) => {
let scopes = localConfig.scopes || [];
return {
clientId: localConfig.clientId,
provider: openidProviderConfig,
scopes: scopes
};
});
};
runBackgroundTokenRefresh = (authenticator: { refresh: () => any; }) => {
setInterval(async () => {
// check every 30s if the token will expire in <= 1m,
// if so, refresh
if (this.expiresAt - Date.now() <= 60_000) {
var resp = await authenticator.refresh();
this.accessToken = resp.accessToken;
this.expiresAt = resp.expiresAt;
this.refreshToken = resp.refreshToken;
}
}, 30_000)
};
refreshTokenProvided = () => {
return this.refreshToken && this.refreshToken != ""
}
}
export interface IAuthUserPasswordCredentials {
username: string
password?: string
scopes?: any[]
}
export class AuthUserPasswordCredentials {
private username: string;
private password?: string;
private scopes?: any[];
constructor(creds: IAuthUserPasswordCredentials) {
this.username = creds.username;
this.password = creds.password;
this.scopes = creds.scopes;
}
}
interface IRequestAccessTokenResponse {
access_token: string
expires_in: number
refresh_token: string
}
class UserPasswordAuthenticator implements IAuthenticator {
private creds: any;
private http: any;
private openidConfig: any;
constructor(http: any, creds: any, config: any) {
this.http = http;
this.creds = creds;
this.openidConfig = config;
if (creds.scopes) {
this.openidConfig.scopes.push(creds.scopes);
}
}
refresh = () => {
this.validateOpenidConfig();
return this.requestAccessToken()
.then((tokenResp: IRequestAccessTokenResponse) => {
return {
accessToken: tokenResp.access_token,
expiresAt: calcExpirationEpoch(tokenResp.expires_in),
refreshToken: tokenResp.refresh_token
};
})
.catch((err: any) => {
return Promise.reject(
new Error(`failed to refresh access token: ${err}`)
);
});
};
validateOpenidConfig = () => {
if (this.openidConfig.provider.grant_types_supported !== undefined &&
!this.openidConfig.provider.grant_types_supported.includes("password")) {
throw new Error("grant_type password not supported");
}
if (this.openidConfig.provider.token_endpoint.includes(
"https://login.microsoftonline.com")) {
throw new Error("microsoft/azure recommends to avoid authentication using " +
"username and password, so this method is not supported by this client");
}
this.openidConfig.scopes.push("offline_access");
};
requestAccessToken = () => {
const url = this.openidConfig.provider.token_endpoint;
const params = new URLSearchParams({
grant_type: "password",
client_id: this.openidConfig.clientId,
username: this.creds.username,
password: this.creds.password,
scope: this.openidConfig.scopes.join(" ")
});
let contentType = "application/x-www-form-urlencoded;charset=UTF-8";
return this.http.externalPost(url, params, contentType);
};
}
export interface IAuthAccessTokenCredentials {
accessToken: string
expiresIn: number
refreshToken?: string
}
export class AuthAccessTokenCredentials {
public readonly accessToken: string;
public readonly expiresAt: number;
public readonly refreshToken?: string;
constructor(creds: IAuthAccessTokenCredentials) {
this.validate(creds);
this.accessToken = creds.accessToken;
this.expiresAt = calcExpirationEpoch(creds.expiresIn);
this.refreshToken = creds.refreshToken;
}
validate = (creds: IAuthAccessTokenCredentials) => {
if (creds.expiresIn === undefined) {
throw new Error("AuthAccessTokenCredentials: expiresIn is required");
}
if (!Number.isInteger(creds.expiresIn) || creds.expiresIn <= 0) {
throw new Error("AuthAccessTokenCredentials: expiresIn must be int > 0");
}
};
}
class AccessTokenAuthenticator implements IAuthenticator {
private creds: any;
private http: any;
private openidConfig: any;
constructor(http: any, creds: any, config: any) {
this.http = http;
this.creds = creds;
this.openidConfig = config;
}
refresh = () => {
if (this.creds.refreshToken === undefined || this.creds.refreshToken == "") {
console.warn("AuthAccessTokenCredentials not provided with refreshToken, cannot refresh");
return Promise.resolve({
accessToken: this.creds.accessToken,
expiresAt: this.creds.expiresAt
});
}
this.validateOpenidConfig();
return this.requestAccessToken()
.then((tokenResp: IRequestAccessTokenResponse) => {
return {
accessToken: tokenResp.access_token,
expiresAt: calcExpirationEpoch(tokenResp.expires_in),
refreshToken: tokenResp.refresh_token
};
})
.catch((err: any) => {
return Promise.reject(
new Error(`failed to refresh access token: ${err}`)
);
});
};
validateOpenidConfig = () => {
if (this.openidConfig.provider.grant_types_supported === undefined ||
!this.openidConfig.provider.grant_types_supported.includes("refresh_token")) {
throw new Error("grant_type refresh_token not supported");
}
};
requestAccessToken = () => {
var url = this.openidConfig.provider.token_endpoint;
var params = new URLSearchParams({
grant_type: "refresh_token",
client_id: this.openidConfig.clientId,
refresh_token: this.creds.refreshToken,
});
let contentType = "application/x-www-form-urlencoded;charset=UTF-8";
return this.http.externalPost(url, params, contentType);
};
}
export interface IAuthClientCredentials {
clientSecret: string
scopes?: any[]
}
export class AuthClientCredentials {
private clientSecret: any;
private scopes?: any[];
constructor(creds: IAuthClientCredentials) {
this.clientSecret = creds.clientSecret;
this.scopes = creds.scopes;
}
}
class ClientCredentialsAuthenticator implements IAuthenticator {
private creds: any;
private http: any;
private openidConfig: any;
constructor(http: any, creds: any, config: any) {
this.http = http;
this.creds = creds;
this.openidConfig = config;
if (creds.scopes) {
this.openidConfig.scopes.push(creds.scopes);
}
}
refresh = () => {
this.validateOpenidConfig();
return this.requestAccessToken()
.then((tokenResp: IRequestAccessTokenResponse) => {
return {
accessToken: tokenResp.access_token,
expiresAt: calcExpirationEpoch(tokenResp.expires_in),
refreshToken: tokenResp.refresh_token
};
})
.catch((err: any) => {
return Promise.reject(
new Error(`failed to refresh access token: ${err}`)
);
});
};
validateOpenidConfig = () => {
if (this.openidConfig.scopes.length > 0) {
return;
}
if (this.openidConfig.provider.token_endpoint
.includes("https://login.microsoftonline.com")) {
this.openidConfig.scopes.push(this.openidConfig.clientId + "/.default");
}
};
requestAccessToken = () => {
const url = this.openidConfig.provider.token_endpoint;
const params = new URLSearchParams({
grant_type: "client_credentials",
client_id: this.openidConfig.clientId,
client_secret: this.creds.clientSecret,
scope: this.openidConfig.scopes.join(" ")
});
let contentType = "application/x-www-form-urlencoded;charset=UTF-8";
return this.http.externalPost(url, params, contentType);
};
}
function calcExpirationEpoch(expiresIn: number): number {
return Date.now() + ((expiresIn - 2) * 1000) // -2 for some lag
}