-
Notifications
You must be signed in to change notification settings - Fork 208
/
Token.ts
299 lines (258 loc) · 10.4 KB
/
Token.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) 2019 Bentley Systems, Incorporated. All rights reserved.
* Licensed under the MIT License. See LICENSE.md in the project root for license terms.
*--------------------------------------------------------------------------------------------*/
/** @module Authentication */
import * as xpath from "xpath";
import { DOMParser } from "xmldom";
import { UserInfo } from "./UserInfo";
import { Base64 } from "js-base64";
import { BentleyError, BentleyStatus } from "@bentley/bentleyjs-core";
/** @internal */
export enum IncludePrefix {
Yes = 0,
No = 1,
}
/** Base class for JWT and SAML tokens
* @beta
*/
export abstract class Token {
protected _samlAssertion?: string;
protected _saml?: string;
protected _jwt?: string;
protected _userInfo?: UserInfo;
protected _startsAt?: Date;
protected _expiresAt?: Date;
protected _x509Certificate?: string;
protected constructor() {
}
/** @internal */
protected getSaml(): string | undefined {
if (this._saml)
return this._saml;
if (!this._samlAssertion)
return undefined;
this._saml = Base64.encode(this._samlAssertion);
return this._saml;
}
/** @internal */
public getSamlAssertion(): string | undefined {
if (this._samlAssertion)
return this._samlAssertion;
if (!this._saml)
return undefined;
this._samlAssertion = Base64.decode(this._saml);
return this._samlAssertion;
}
/** @internal */
public getUserInfo(): UserInfo | undefined {
if (this._userInfo || this._jwt)
return this._userInfo;
if (!this.parseSamlAssertion())
return undefined;
return this._userInfo;
}
/** @internal */
public setUserInfo(userInfo: UserInfo) {
this._userInfo = userInfo;
}
/** @internal */
public getExpiresAt(): Date | undefined {
if (this._expiresAt || this._jwt)
return this._expiresAt;
if (!this.parseSamlAssertion())
return undefined;
return this._expiresAt;
}
/** @internal */
public getStartsAt(): Date | undefined {
if (this._startsAt || this._jwt)
return this._startsAt;
if (!this.parseSamlAssertion())
return undefined;
return this._startsAt;
}
/** @internal */
protected parseSamlAssertion(): boolean {
this._samlAssertion = this.getSamlAssertion();
if (!this._samlAssertion)
return false;
const select: xpath.XPathSelect = xpath.useNamespaces({
ds: "http://www.w3.org/2000/09/xmldsig#",
saml: "urn:oasis:names:tc:SAML:1.0:assertion",
});
const dom: Document = (new DOMParser()).parseFromString(this._samlAssertion);
this._x509Certificate = select("/saml:Assertion/ds:Signature/ds:KeyInfo/ds:X509Data/ds:X509Certificate/text()", dom).toString();
const startsAtStr: string = select("string(/saml:Assertion/saml:Conditions/@NotBefore)", dom).toString();
this._startsAt = new Date(startsAtStr);
const expiresAtStr: string = select("string(/saml:Assertion/saml:Conditions/@NotOnOrAfter)", dom).toString();
const extractAttribute: (attributeName: string) => string = (attributeName: string) =>
select("/saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='" +
attributeName + "']/saml:AttributeValue/text()", dom).toString();
const id = extractAttribute("userid");
const email = {
id: extractAttribute("emailaddress"),
};
const profile = {
name: extractAttribute("name"),
firstName: extractAttribute("givenname"),
lastName: extractAttribute("surname"),
};
const organization = {
id: extractAttribute("organizationid"),
name: extractAttribute("organization"),
};
const featureTracking = {
ultimateSite: extractAttribute("ultimatesite"),
usageCountryIso: extractAttribute("usagecountryiso"),
};
this._userInfo = new UserInfo(id, email, profile, organization, featureTracking);
this._startsAt = new Date(startsAtStr);
this._expiresAt = new Date(expiresAtStr);
return !!this._x509Certificate && !!this._startsAt && !!this._expiresAt;
}
}
/** Token issued by Active Secure Token Service or Federated Authentication Service for user authentication/authorization
* @internal
*/
export class AuthorizationToken extends Token {
/** Sets up a new AuthorizationToken based on the SAML that was passed in.
* Does NOT validate the resulting token.
* @internal
*/
public static fromSamlAssertion(samlAssertion: string): AuthorizationToken {
const token = new AuthorizationToken();
token._samlAssertion = samlAssertion;
return token;
}
/** Creates a string representation of the contained token
* @internal
*/
public toTokenString(includePrefix: IncludePrefix = IncludePrefix.Yes): string {
if (!this.parseSamlAssertion() || !this._x509Certificate)
throw new BentleyError(BentleyStatus.ERROR, "Invalid access token");
const prefix = (includePrefix === IncludePrefix.Yes) ? "X509 access_token=" : "";
return prefix + Buffer.from(this._x509Certificate, "utf8").toString("base64");
}
}
/** Token issued by DelegationSecureTokenService for API access
* @beta
*/
export class AccessToken extends Token {
private static _samlTokenPrefix = "Token";
private static _jwtTokenPrefix = "Bearer";
public static foreignProjectAccessTokenJsonProperty = "ForeignProjectAccessToken";
private _foreignJwt?: string;
/** Returns true if it's a Json Web Token, and false if it's a SAML token
* @internal
*/
public get isJwt(): boolean {
return !!this._jwt;
}
/** Sets up a new AccessToken based on the SAML that was passed in.
* Does NOT validate the resulting token.
* @internal
*/
public static fromSamlAssertion(samlAssertion: string): AccessToken {
const token = new AccessToken();
token._samlAssertion = samlAssertion;
return token;
}
/** Sets up a new AccessToken based on some generic token abstraction used for iModelBank use cases
* @internal
*/
public static fromForeignProjectAccessTokenJson(foreignJsonStr: string): AccessToken | undefined {
if (!foreignJsonStr.startsWith(`{\"${this.foreignProjectAccessTokenJsonProperty}\":`))
return undefined;
const props: any = JSON.parse(foreignJsonStr);
if (props[this.foreignProjectAccessTokenJsonProperty] === undefined)
return undefined;
const tok = new AccessToken();
tok._foreignJwt = foreignJsonStr;
tok._userInfo = props[this.foreignProjectAccessTokenJsonProperty].userInfo;
return tok;
}
/** Create an AccessToken from a SAML string for Windows Federated Authentication workflows.
* Does NOT validate the token.
* @internal
*/
public static fromSamlTokenString(accessTokenStr: string, includesPrefix: IncludePrefix = IncludePrefix.Yes): AccessToken {
let saml = accessTokenStr;
if (includesPrefix === IncludePrefix.Yes) {
const prefixLength = AccessToken._samlTokenPrefix.length;
if (accessTokenStr.substr(0, prefixLength).toLowerCase() !== AccessToken._samlTokenPrefix.toLowerCase())
throw new BentleyError(BentleyStatus.ERROR, "Invalid saml token");
saml = accessTokenStr.slice(6);
if (!saml)
throw new BentleyError(BentleyStatus.ERROR, "Invalid saml token");
}
const token = new AccessToken();
token._saml = saml;
return token;
}
/** Create an AccessToken from a JWT token for OIDC workflows
* Does NOT validate the token.
* @internal
*/
public static fromJsonWebTokenString(jwt: string, startsAt?: Date, expiresAt?: Date, userInfo?: UserInfo): AccessToken {
const token = new AccessToken();
token._jwt = jwt;
token._startsAt = startsAt;
token._expiresAt = expiresAt;
token._userInfo = userInfo;
return token;
}
/**
* Convert this AccessToken to a string
* @param includePrefix Include the token prefix to identify JWT or SAML tokens
* @internal
*/
public toTokenString(includePrefix: IncludePrefix = IncludePrefix.Yes): string {
if (this._jwt)
return (includePrefix === IncludePrefix.Yes) ? AccessToken._jwtTokenPrefix + " " + this._jwt : this._jwt;
const saml = this.getSaml();
if (saml)
return (includePrefix === IncludePrefix.Yes) ? AccessToken._samlTokenPrefix + " " + saml : saml;
if (this._foreignJwt) {
return Base64.encode(this._foreignJwt); // TODO: migrate iModelBank to support Oidc tokens (_jwt)
}
throw new BentleyError(BentleyStatus.ERROR, "Cannot convert invalid access token to string");
}
/**
* Create an AccessToken from a string. The token must include the prefix to differentiate between JWT and SAML.
* @param tokenStr String representation of the token
* @internal
*/
public static fromTokenString(tokenStr: string): AccessToken {
if (tokenStr.startsWith(AccessToken._jwtTokenPrefix)) {
const jwtString = tokenStr.substr(AccessToken._jwtTokenPrefix.length + 1);
return AccessToken.fromJsonWebTokenString(jwtString);
}
if (tokenStr.startsWith(AccessToken._samlTokenPrefix)) {
tokenStr.substr(AccessToken._samlTokenPrefix.length + 1);
const samlString = tokenStr.substr(AccessToken._samlTokenPrefix.length + 1);
return AccessToken.fromSamlTokenString(samlString, IncludePrefix.No);
}
if (tokenStr.startsWith(`{\"${AccessToken.foreignProjectAccessTokenJsonProperty}\":`)) {
const accessToken = AccessToken.fromForeignProjectAccessTokenJson(tokenStr);
if (!accessToken)
throw new BentleyError(BentleyStatus.ERROR, "Invalid access token");
}
throw new BentleyError(BentleyStatus.ERROR, "Invalid access token");
}
/**
* Creates an AccessToken from an untyped JSON object
* @param jsonObj
* @internal
*/
public static fromJson(jsonObj: any): AccessToken | undefined {
if (jsonObj._jwt)
return AccessToken.fromJsonWebTokenString(jsonObj._jwt, jsonObj._startsAt, jsonObj._expiresAt, jsonObj._userInfo);
if (jsonObj._foreignJwt) {
const foreignTok = AccessToken.fromForeignProjectAccessTokenJson(jsonObj._foreignJwt);
if (foreignTok !== undefined)
return foreignTok;
}
return AccessToken.fromSamlAssertion(jsonObj._samlAssertion) as AccessToken;
}
}