@kolektor/nucleus-identity 0.0.8-pre.5676 → 0.0.9-pre.5874
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/{esm2015/kolektor-nucleus-identity.js → esm2020/kolektor-nucleus-identity.mjs} +0 -0
- package/{esm2015/lib/models/client-registration.js → esm2020/lib/models/client-registration.mjs} +0 -0
- package/{esm2015/lib/models/device-code.js → esm2020/lib/models/device-code.mjs} +0 -0
- package/{esm2015/lib/models/identity.js → esm2020/lib/models/identity.mjs} +0 -0
- package/{esm2015/lib/models/otp.js → esm2020/lib/models/otp.mjs} +0 -0
- package/{esm2015/lib/models/service-principal.js → esm2020/lib/models/service-principal.mjs} +0 -0
- package/{esm2015/lib/nucleus-identity-config.js → esm2020/lib/nucleus-identity-config.mjs} +0 -0
- package/{esm2015/lib/nucleus-identity.module.js → esm2020/lib/nucleus-identity.module.mjs} +4 -4
- package/esm2020/lib/nucleus-identity.service.mjs +338 -0
- package/esm2020/lib/nucleus-token-interceptor.service.mjs +64 -0
- package/{esm2015/lib/utils/angular-requestor.js → esm2020/lib/utils/angular-requestor.mjs} +5 -6
- package/{esm2015/lib/utils/authorization-service-configuration.js → esm2020/lib/utils/authorization-service-configuration.mjs} +0 -0
- package/{esm2015/lib/utils/location.service.js → esm2020/lib/utils/location.service.mjs} +3 -3
- package/{esm2015/lib/utils/nucleus-authorization-notifier.js → esm2020/lib/utils/nucleus-authorization-notifier.mjs} +0 -0
- package/{esm2015/lib/utils/nucleus-crypto.js → esm2020/lib/utils/nucleus-crypto.mjs} +0 -0
- package/esm2020/lib/utils/oidc-configuration.service.mjs +90 -0
- package/esm2020/lib/utils/secrets-store.mjs +117 -0
- package/esm2020/lib/utils/token-client.mjs +140 -0
- package/{esm2015/public-api.js → esm2020/public-api.mjs} +0 -0
- package/fesm2015/{kolektor-nucleus-identity.js → kolektor-nucleus-identity.mjs} +177 -166
- package/fesm2015/kolektor-nucleus-identity.mjs.map +1 -0
- package/fesm2020/kolektor-nucleus-identity.mjs +1054 -0
- package/fesm2020/kolektor-nucleus-identity.mjs.map +1 -0
- package/lib/nucleus-identity.service.d.ts +3 -2
- package/lib/utils/secrets-store.d.ts +3 -0
- package/package.json +22 -9
- package/bundles/kolektor-nucleus-identity.umd.js +0 -1910
- package/bundles/kolektor-nucleus-identity.umd.js.map +0 -1
- package/esm2015/lib/nucleus-identity.service.js +0 -385
- package/esm2015/lib/nucleus-token-interceptor.service.js +0 -66
- package/esm2015/lib/utils/oidc-configuration.service.js +0 -95
- package/esm2015/lib/utils/secrets-store.js +0 -113
- package/esm2015/lib/utils/token-client.js +0 -159
- package/fesm2015/kolektor-nucleus-identity.js.map +0 -1
|
@@ -0,0 +1,1054 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { Injectable, NgModule } from '@angular/core';
|
|
3
|
+
import * as i1$1 from '@angular/common/http';
|
|
4
|
+
import { HttpErrorResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
|
|
5
|
+
import { lastValueFrom, from, throwError } from 'rxjs';
|
|
6
|
+
import { AppAuthError, AuthorizationNotifier, TokenResponse, Requestor, AuthorizationServiceConfiguration, JQueryRequestor, nowInSeconds, BaseTokenRequestHandler, BasicQueryStringUtils, TokenRequest, GRANT_TYPE_AUTHORIZATION_CODE, GRANT_TYPE_REFRESH_TOKEN, LocalStorageBackend, RedirectRequestHandler, AuthorizationRequest } from '@openid/appauth';
|
|
7
|
+
import { App } from '@capacitor/app';
|
|
8
|
+
import { Browser } from '@capacitor/browser';
|
|
9
|
+
import { Device } from '@capacitor/device';
|
|
10
|
+
import * as base64 from 'base64-js';
|
|
11
|
+
import * as i1 from '@kolektor/nucleus-common';
|
|
12
|
+
import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin';
|
|
13
|
+
import { mergeMap, catchError } from 'rxjs/operators';
|
|
14
|
+
|
|
15
|
+
class NucleusIdentityConfig {
|
|
16
|
+
constructor() {
|
|
17
|
+
this.authority = null;
|
|
18
|
+
this.httpInterceptorUrls = [];
|
|
19
|
+
this.automaticLoginOnHttp401 = false;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
24
|
+
class NucleusCrypto {
|
|
25
|
+
constructor() {
|
|
26
|
+
this.browserCrypto = window.crypto || window.msCrypto;
|
|
27
|
+
}
|
|
28
|
+
generateRandom(size) {
|
|
29
|
+
const buffer = new Uint8Array(size);
|
|
30
|
+
if (this.browserCrypto) {
|
|
31
|
+
this.browserCrypto.getRandomValues(buffer);
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
// fall back to Math.random() if nothing else is available
|
|
35
|
+
for (let i = 0; i < size; i += 1) {
|
|
36
|
+
buffer[i] = Math.random();
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return this.bufferToString(buffer);
|
|
40
|
+
}
|
|
41
|
+
deriveChallenge(code) {
|
|
42
|
+
if (code.length < 43 || code.length > 128) {
|
|
43
|
+
return Promise.reject(new AppAuthError('Invalid code length.'));
|
|
44
|
+
}
|
|
45
|
+
if (!this.browserCrypto.subtle) {
|
|
46
|
+
return Promise.reject(new AppAuthError('window.crypto.subtle is unavailable.'));
|
|
47
|
+
}
|
|
48
|
+
const ecode = this.textEncodeLite(code);
|
|
49
|
+
const op = this.browserCrypto.subtle.digest('SHA-256', ecode);
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
// if operation contains algorithm it means it is not a promise which means it is CryptoOperation from IE.
|
|
52
|
+
// We just return result as promise
|
|
53
|
+
if (op.algorithm) {
|
|
54
|
+
console.log('we have a CryptoOperation');
|
|
55
|
+
op.addEventListener('complete', () => {
|
|
56
|
+
resolve(this.urlSafe(op.result));
|
|
57
|
+
});
|
|
58
|
+
op.addEventListener('error', () => {
|
|
59
|
+
reject(op.result);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
else { // the result is promise
|
|
63
|
+
op.then(buffer => resolve(this.urlSafe(buffer)), error => reject(error));
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
urlSafe(buffer) {
|
|
68
|
+
const encoded = base64.fromByteArray(new Uint8Array(buffer));
|
|
69
|
+
return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
|
|
70
|
+
}
|
|
71
|
+
textEncodeLite(str) {
|
|
72
|
+
const buf = new ArrayBuffer(str.length);
|
|
73
|
+
const bufView = new Uint8Array(buf);
|
|
74
|
+
for (let i = 0; i < str.length; i++) {
|
|
75
|
+
bufView[i] = str.charCodeAt(i);
|
|
76
|
+
}
|
|
77
|
+
return bufView;
|
|
78
|
+
}
|
|
79
|
+
bufferToString(buffer) {
|
|
80
|
+
const state = [];
|
|
81
|
+
for (let i = 0; i < buffer.byteLength; i += 1) {
|
|
82
|
+
const index = buffer[i] % CHARSET.length;
|
|
83
|
+
state.push(CHARSET[index]);
|
|
84
|
+
}
|
|
85
|
+
return state.join('');
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
class LocationService {
|
|
90
|
+
constructor(appService) {
|
|
91
|
+
this.appService = appService;
|
|
92
|
+
}
|
|
93
|
+
get hash() {
|
|
94
|
+
return window.location.hash;
|
|
95
|
+
}
|
|
96
|
+
set hash(v) {
|
|
97
|
+
window.location.hash = v;
|
|
98
|
+
}
|
|
99
|
+
get host() {
|
|
100
|
+
return window.location.host;
|
|
101
|
+
}
|
|
102
|
+
set host(v) {
|
|
103
|
+
window.location.host = v;
|
|
104
|
+
}
|
|
105
|
+
get origin() {
|
|
106
|
+
return window.location.origin;
|
|
107
|
+
}
|
|
108
|
+
get hostname() {
|
|
109
|
+
return window.location.hostname;
|
|
110
|
+
}
|
|
111
|
+
set hostname(v) {
|
|
112
|
+
window.location.hostname = v;
|
|
113
|
+
}
|
|
114
|
+
get pathname() {
|
|
115
|
+
return window.location.pathname;
|
|
116
|
+
}
|
|
117
|
+
set pathname(v) {
|
|
118
|
+
window.location.pathname = v;
|
|
119
|
+
}
|
|
120
|
+
get port() {
|
|
121
|
+
return window.location.port;
|
|
122
|
+
}
|
|
123
|
+
set port(v) {
|
|
124
|
+
window.location.port = v;
|
|
125
|
+
}
|
|
126
|
+
get protocol() {
|
|
127
|
+
return window.location.protocol;
|
|
128
|
+
}
|
|
129
|
+
set protocol(v) {
|
|
130
|
+
window.location.protocol = v;
|
|
131
|
+
}
|
|
132
|
+
get search() {
|
|
133
|
+
return window.location.search;
|
|
134
|
+
}
|
|
135
|
+
set search(v) {
|
|
136
|
+
window.location.search = v;
|
|
137
|
+
}
|
|
138
|
+
assign(url) {
|
|
139
|
+
if (this.appService.isNative) {
|
|
140
|
+
Browser.open({ url });
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
window.location.assign(url);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
LocationService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LocationService, deps: [{ token: i1.NucleusAppService }], target: i0.ɵɵFactoryTarget.Injectable });
|
|
148
|
+
LocationService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LocationService, providedIn: 'root' });
|
|
149
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LocationService, decorators: [{
|
|
150
|
+
type: Injectable,
|
|
151
|
+
args: [{
|
|
152
|
+
providedIn: 'root'
|
|
153
|
+
}]
|
|
154
|
+
}], ctorParameters: function () { return [{ type: i1.NucleusAppService }]; } });
|
|
155
|
+
|
|
156
|
+
class NucleusAuthorizationNotifier extends AuthorizationNotifier {
|
|
157
|
+
constructor() {
|
|
158
|
+
super();
|
|
159
|
+
this.setAuthorizationListener((request, response, error) => {
|
|
160
|
+
console.log('Authorization request complete ', request, response, error);
|
|
161
|
+
this.response = response;
|
|
162
|
+
this.request = request;
|
|
163
|
+
this.error = error;
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
class Claim {
|
|
169
|
+
constructor(name, values) {
|
|
170
|
+
this.name = name;
|
|
171
|
+
this.values = values;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
class Identity {
|
|
175
|
+
constructor() {
|
|
176
|
+
this.claims = [];
|
|
177
|
+
}
|
|
178
|
+
static createFromResponse(res) {
|
|
179
|
+
const token = this.decodeToken(res.idToken);
|
|
180
|
+
const id = new Identity();
|
|
181
|
+
id.name = token.name;
|
|
182
|
+
id.subject = token.sub;
|
|
183
|
+
for (const key in token) {
|
|
184
|
+
if ({}.hasOwnProperty.call(token, key)) {
|
|
185
|
+
let vals = token[key];
|
|
186
|
+
if (!Array.isArray(vals)) {
|
|
187
|
+
vals = [vals];
|
|
188
|
+
}
|
|
189
|
+
const claim = new Claim(key, vals);
|
|
190
|
+
id.claims.push(claim);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return id;
|
|
194
|
+
}
|
|
195
|
+
static decodeToken(jwt) {
|
|
196
|
+
if (!jwt) {
|
|
197
|
+
throw new Error('NucleusIdentity: There was no identity token in the response!');
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
const arr = jwt.split('.');
|
|
201
|
+
// var header = arr[0];
|
|
202
|
+
const payload = this.b64DecodeUnicode(arr[1]);
|
|
203
|
+
// var signature = arr[2];
|
|
204
|
+
return JSON.parse(payload);
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
console.error('Error while decoding identity token', error);
|
|
208
|
+
console.error('Error while decoding identity token JWT', jwt);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
static b64DecodeUnicode(str) {
|
|
212
|
+
str = str.replace(/-/g, '+').replace(/_/g, '/'); // Qlector fix :)
|
|
213
|
+
return decodeURIComponent(atob(str).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''));
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
class SecretsStore {
|
|
218
|
+
constructor(clientId) {
|
|
219
|
+
this._tokens = {};
|
|
220
|
+
this._identities = {};
|
|
221
|
+
// this specify which identity id is used by default, when If id is not specified in getToken or getIdentity
|
|
222
|
+
this._defaultIdentityId = null;
|
|
223
|
+
this._defaultIdentityIdStorageKey = null;
|
|
224
|
+
this._tokenStorageKeyPrefix = `Nucleus.Identity.${clientId}`; // do not change this or login with existing tokens will fail
|
|
225
|
+
this._servicePrincipalKey = `${this._tokenStorageKeyPrefix}.SvcP`;
|
|
226
|
+
this._defaultIdentityIdStorageKey = `${this._tokenStorageKeyPrefix}.IdId`;
|
|
227
|
+
this._defaultIdentityId = localStorage.getItem(this._defaultIdentityIdStorageKey);
|
|
228
|
+
}
|
|
229
|
+
removeServicePrincipal() {
|
|
230
|
+
this._servicePrincipal = null;
|
|
231
|
+
return this.clear(this._servicePrincipalKey);
|
|
232
|
+
}
|
|
233
|
+
async setServicePrincipal(servicePrincipal) {
|
|
234
|
+
this._servicePrincipal = servicePrincipal;
|
|
235
|
+
await this.save(this._servicePrincipalKey, servicePrincipal);
|
|
236
|
+
}
|
|
237
|
+
async getServicePrincipal() {
|
|
238
|
+
if (!this._servicePrincipal) {
|
|
239
|
+
this._servicePrincipal = await this.load(this._servicePrincipalKey);
|
|
240
|
+
}
|
|
241
|
+
return this._servicePrincipal;
|
|
242
|
+
}
|
|
243
|
+
setToken(token, id = null) {
|
|
244
|
+
return this.setTokenInternal(token, true, id);
|
|
245
|
+
}
|
|
246
|
+
getIdentity(id = null) {
|
|
247
|
+
const key = this.getTokenKey(id);
|
|
248
|
+
return this._identities[key];
|
|
249
|
+
}
|
|
250
|
+
setDefaultIdentityId(id) {
|
|
251
|
+
this._defaultIdentityId = id;
|
|
252
|
+
if (this._defaultIdentityId) {
|
|
253
|
+
localStorage.setItem(this._defaultIdentityIdStorageKey, this._defaultIdentityId);
|
|
254
|
+
}
|
|
255
|
+
else {
|
|
256
|
+
localStorage.removeItem(this._defaultIdentityIdStorageKey);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
async getToken(id = null) {
|
|
260
|
+
const key = this.getTokenKey(id);
|
|
261
|
+
// if token is not there or it is invalid we check storage again before returning
|
|
262
|
+
if (!this._tokens[key] || !this._tokens[key].isValid()) {
|
|
263
|
+
await this.reloadTokenFromStorage(id);
|
|
264
|
+
}
|
|
265
|
+
return this._tokens[key];
|
|
266
|
+
}
|
|
267
|
+
removeToken(id = null) {
|
|
268
|
+
const key = this.getTokenKey(id);
|
|
269
|
+
delete this._tokens[key];
|
|
270
|
+
delete this._identities[key];
|
|
271
|
+
return this.clear(key);
|
|
272
|
+
}
|
|
273
|
+
async reloadTokenFromStorage(id) {
|
|
274
|
+
const key = this.getTokenKey(id);
|
|
275
|
+
const storedToken = await this.load(key);
|
|
276
|
+
if (storedToken) {
|
|
277
|
+
const res = new TokenResponse(storedToken);
|
|
278
|
+
if (res?.accessToken || res?.idToken) {
|
|
279
|
+
await this.setTokenInternal(res, false, id);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
async setTokenInternal(token, save, id = null) {
|
|
285
|
+
const key = this.getTokenKey(id);
|
|
286
|
+
if (token == null) {
|
|
287
|
+
await this.removeToken(id);
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
this._tokens[key] = token;
|
|
291
|
+
this._identities[key] = Identity.createFromResponse(token);
|
|
292
|
+
if (save) {
|
|
293
|
+
try {
|
|
294
|
+
await this.save(key, token.toJson());
|
|
295
|
+
}
|
|
296
|
+
catch (e) {
|
|
297
|
+
console.warn('Nucleus.Identity: Could not save to SecureStorage.');
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
getTokenKey(id = null) {
|
|
303
|
+
if (!id) {
|
|
304
|
+
id = this._defaultIdentityId;
|
|
305
|
+
}
|
|
306
|
+
return id ? `${this._tokenStorageKeyPrefix}.${id}` : this._tokenStorageKeyPrefix;
|
|
307
|
+
}
|
|
308
|
+
clear(key) {
|
|
309
|
+
return SecureStoragePlugin.remove({ key });
|
|
310
|
+
}
|
|
311
|
+
save(key, value) {
|
|
312
|
+
return SecureStoragePlugin.set({ key, value: JSON.stringify(value) });
|
|
313
|
+
}
|
|
314
|
+
async load(key) {
|
|
315
|
+
try {
|
|
316
|
+
const x = await SecureStoragePlugin.get({ key });
|
|
317
|
+
if (x?.value) {
|
|
318
|
+
return JSON.parse(x.value);
|
|
319
|
+
}
|
|
320
|
+
else {
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
catch {
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
class AngularRequestor extends Requestor {
|
|
331
|
+
constructor(http) {
|
|
332
|
+
super();
|
|
333
|
+
this.http = http;
|
|
334
|
+
}
|
|
335
|
+
// eslint-disable-next-line no-undef
|
|
336
|
+
xhr(settings) {
|
|
337
|
+
if (settings.method === undefined) {
|
|
338
|
+
settings.method = 'GET';
|
|
339
|
+
}
|
|
340
|
+
return new Promise((resolve, reject) => {
|
|
341
|
+
this.http.request(settings.method, settings.url, {
|
|
342
|
+
body: settings.data,
|
|
343
|
+
headers: settings.headers,
|
|
344
|
+
}).subscribe(res => resolve(res), err => {
|
|
345
|
+
let e = new AppAuthError(err);
|
|
346
|
+
if (err instanceof HttpErrorResponse) {
|
|
347
|
+
e = new AppAuthError(err.error?.error || err.statusText);
|
|
348
|
+
}
|
|
349
|
+
reject(e);
|
|
350
|
+
});
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
AngularRequestor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: AngularRequestor, deps: [{ token: i1$1.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
|
|
355
|
+
AngularRequestor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: AngularRequestor, providedIn: 'root' });
|
|
356
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: AngularRequestor, decorators: [{
|
|
357
|
+
type: Injectable,
|
|
358
|
+
args: [{
|
|
359
|
+
providedIn: 'root'
|
|
360
|
+
}]
|
|
361
|
+
}], ctorParameters: function () { return [{ type: i1$1.HttpClient }]; } });
|
|
362
|
+
|
|
363
|
+
const WELL_KNOWN_PATH = '.well-known';
|
|
364
|
+
const OPENID_CONFIGURATION = 'openid-configuration';
|
|
365
|
+
class NucleusAuthorizationServiceConfiguration extends AuthorizationServiceConfiguration {
|
|
366
|
+
constructor(request) {
|
|
367
|
+
super(request);
|
|
368
|
+
this.deviceAuthorizationEndpoint = request.device_authorization_endpoint;
|
|
369
|
+
this.registrationEndpoint = request.registration_endpoint;
|
|
370
|
+
}
|
|
371
|
+
static fetchFromIssuer(openIdIssuerUrl, requestor) {
|
|
372
|
+
const fullUrl = `${openIdIssuerUrl}/${WELL_KNOWN_PATH}/${OPENID_CONFIGURATION}`;
|
|
373
|
+
const requestorToUse = requestor || new JQueryRequestor();
|
|
374
|
+
return requestorToUse
|
|
375
|
+
.xhr({ url: fullUrl, dataType: 'json', method: 'GET' })
|
|
376
|
+
.then(json => new NucleusAuthorizationServiceConfiguration(json));
|
|
377
|
+
}
|
|
378
|
+
toJson() {
|
|
379
|
+
const res = super.toJson();
|
|
380
|
+
res.device_authorization_endpoint = this.deviceAuthorizationEndpoint;
|
|
381
|
+
return res;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
class OidcConfigurationService {
|
|
386
|
+
constructor(requestor, config, appService) {
|
|
387
|
+
this.requestor = requestor;
|
|
388
|
+
this.config = config;
|
|
389
|
+
this.appService = appService;
|
|
390
|
+
this._configuration = null;
|
|
391
|
+
}
|
|
392
|
+
async getConfiguration() {
|
|
393
|
+
await this.assureConfiguration();
|
|
394
|
+
return this._configuration;
|
|
395
|
+
}
|
|
396
|
+
get clientId() {
|
|
397
|
+
return this.config.clientId;
|
|
398
|
+
}
|
|
399
|
+
get requestedScopes() {
|
|
400
|
+
return this.config.requestedScopes;
|
|
401
|
+
}
|
|
402
|
+
get servicePrincipalRequestedScopes() {
|
|
403
|
+
return this.config.servicePrincipalRequestedScopes;
|
|
404
|
+
}
|
|
405
|
+
get authProviderHint() {
|
|
406
|
+
return this.config.authProviderHint;
|
|
407
|
+
}
|
|
408
|
+
get redirectUrl() {
|
|
409
|
+
let uri = window.location.href;
|
|
410
|
+
const platform = this.appService.platform;
|
|
411
|
+
if (platform === 'android' && this.config.androidRedirectUri) {
|
|
412
|
+
uri = this.config.androidRedirectUri;
|
|
413
|
+
}
|
|
414
|
+
else if (platform === 'ios' && this.config.iOSRedirectUri) {
|
|
415
|
+
uri = this.config.iOSRedirectUri;
|
|
416
|
+
}
|
|
417
|
+
else if (this.config.redirectUri) {
|
|
418
|
+
uri = this.config.redirectUri;
|
|
419
|
+
}
|
|
420
|
+
return this.NormalizeRedirectUri(uri);
|
|
421
|
+
}
|
|
422
|
+
getServerUrl(relativeUri = null) {
|
|
423
|
+
let authority = this.config.authority;
|
|
424
|
+
if (!authority || authority === 'origin') {
|
|
425
|
+
authority = window.origin;
|
|
426
|
+
}
|
|
427
|
+
let url = new URL(authority);
|
|
428
|
+
if (relativeUri) {
|
|
429
|
+
url = new URL(relativeUri, url);
|
|
430
|
+
}
|
|
431
|
+
return url.href;
|
|
432
|
+
}
|
|
433
|
+
NormalizeRedirectUri(uri) {
|
|
434
|
+
const i = uri.indexOf('#');
|
|
435
|
+
if (i > 0) {
|
|
436
|
+
uri = uri.substring(0, i);
|
|
437
|
+
}
|
|
438
|
+
return uri;
|
|
439
|
+
}
|
|
440
|
+
async assureConfiguration() {
|
|
441
|
+
if (this._configuration != null) {
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
let authority = this.getServerUrl();
|
|
445
|
+
if (authority[authority.length - 1] === '/') {
|
|
446
|
+
authority = authority.slice(0, -1);
|
|
447
|
+
}
|
|
448
|
+
try {
|
|
449
|
+
this._configuration = await NucleusAuthorizationServiceConfiguration.fetchFromIssuer(authority, this.requestor);
|
|
450
|
+
}
|
|
451
|
+
catch (e) {
|
|
452
|
+
console.error('Nucleus.Identity: Cannot load OIDC configuration: ' + e.message);
|
|
453
|
+
throw e;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
OidcConfigurationService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: OidcConfigurationService, deps: [{ token: AngularRequestor }, { token: NucleusIdentityConfig }, { token: i1.NucleusAppService }], target: i0.ɵɵFactoryTarget.Injectable });
|
|
458
|
+
OidcConfigurationService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: OidcConfigurationService, providedIn: 'root' });
|
|
459
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: OidcConfigurationService, decorators: [{
|
|
460
|
+
type: Injectable,
|
|
461
|
+
args: [{
|
|
462
|
+
providedIn: 'root'
|
|
463
|
+
}]
|
|
464
|
+
}], ctorParameters: function () { return [{ type: AngularRequestor }, { type: NucleusIdentityConfig }, { type: i1.NucleusAppService }]; } });
|
|
465
|
+
|
|
466
|
+
class DeviceCode {
|
|
467
|
+
constructor(response) {
|
|
468
|
+
this.deviceCode = response.device_code;
|
|
469
|
+
this.userCode = response.user_code;
|
|
470
|
+
this.verificationUrl = response.verification_uri;
|
|
471
|
+
this.verificationUrlComplete = response.verification_uri_complete;
|
|
472
|
+
this.expiresIn = parseInt(response.expires_in, 10);
|
|
473
|
+
this.issuedAt = nowInSeconds();
|
|
474
|
+
}
|
|
475
|
+
isExpired(buffer = 60) {
|
|
476
|
+
return this.secondsLeft(buffer) <= 0;
|
|
477
|
+
}
|
|
478
|
+
secondsLeft(buffer = 60) {
|
|
479
|
+
const now = nowInSeconds();
|
|
480
|
+
return (this.issuedAt + this.expiresIn - buffer) - now;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
class ClientRegistrationResponse {
|
|
485
|
+
constructor(response) {
|
|
486
|
+
this.clientId = response.client_id;
|
|
487
|
+
this.clientSecret = response.client_secret;
|
|
488
|
+
this.secretExpirationDate = new Date(response.client_secret_expires_at * 1000);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
class TokenClient {
|
|
493
|
+
constructor(requestor, config) {
|
|
494
|
+
this.requestor = requestor;
|
|
495
|
+
this.config = config;
|
|
496
|
+
this._tokenHandler = new BaseTokenRequestHandler(requestor);
|
|
497
|
+
this._utils = new BasicQueryStringUtils();
|
|
498
|
+
}
|
|
499
|
+
async getByAuthorizationCode(redirectUrl, code, codeVerifier) {
|
|
500
|
+
const config = await this.config.getConfiguration();
|
|
501
|
+
const redirectUri = redirectUrl;
|
|
502
|
+
const req = new TokenRequest({
|
|
503
|
+
client_id: this.config.clientId,
|
|
504
|
+
redirect_uri: redirectUri,
|
|
505
|
+
grant_type: GRANT_TYPE_AUTHORIZATION_CODE,
|
|
506
|
+
code,
|
|
507
|
+
extras: { code_verifier: codeVerifier }
|
|
508
|
+
});
|
|
509
|
+
return await this._tokenHandler.performTokenRequest(config, req);
|
|
510
|
+
}
|
|
511
|
+
async getByRefreshToken(refreshToken) {
|
|
512
|
+
const config = await this.config.getConfiguration();
|
|
513
|
+
const redirectUri = this.config.redirectUrl;
|
|
514
|
+
const req = new TokenRequest({
|
|
515
|
+
client_id: this.config.clientId,
|
|
516
|
+
redirect_uri: redirectUri,
|
|
517
|
+
grant_type: GRANT_TYPE_REFRESH_TOKEN,
|
|
518
|
+
refresh_token: refreshToken
|
|
519
|
+
});
|
|
520
|
+
return await this._tokenHandler.performTokenRequest(config, req);
|
|
521
|
+
}
|
|
522
|
+
async getByClientCredentials(clientId, clientSecret, scope) {
|
|
523
|
+
const config = await this.config.getConfiguration();
|
|
524
|
+
const req = new TokenRequest({
|
|
525
|
+
client_id: clientId,
|
|
526
|
+
redirect_uri: null,
|
|
527
|
+
grant_type: 'client_credentials',
|
|
528
|
+
extras: {
|
|
529
|
+
client_secret: clientSecret,
|
|
530
|
+
scope,
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
return await this._tokenHandler.performTokenRequest(config, req);
|
|
534
|
+
}
|
|
535
|
+
async getBySecret(provider, secret, assertionToken, scope) {
|
|
536
|
+
const config = await this.config.getConfiguration();
|
|
537
|
+
const req = new TokenRequest({
|
|
538
|
+
client_id: this.config.clientId,
|
|
539
|
+
redirect_uri: null,
|
|
540
|
+
grant_type: 'urn:kolektor:nucleus:secret',
|
|
541
|
+
extras: {
|
|
542
|
+
secret_provider: provider,
|
|
543
|
+
secret_value: secret,
|
|
544
|
+
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
|
|
545
|
+
client_assertion: assertionToken,
|
|
546
|
+
scope,
|
|
547
|
+
}
|
|
548
|
+
});
|
|
549
|
+
return await this._tokenHandler.performTokenRequest(config, req);
|
|
550
|
+
}
|
|
551
|
+
async getByDeviceCode(deviceCode) {
|
|
552
|
+
const config = await this.config.getConfiguration();
|
|
553
|
+
const req = new TokenRequest({
|
|
554
|
+
client_id: this.config.clientId,
|
|
555
|
+
redirect_uri: null,
|
|
556
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
|
|
557
|
+
extras: {
|
|
558
|
+
device_code: deviceCode
|
|
559
|
+
}
|
|
560
|
+
});
|
|
561
|
+
return await this._tokenHandler.performTokenRequest(config, req);
|
|
562
|
+
}
|
|
563
|
+
async registerServicePrincipal(token) {
|
|
564
|
+
const config = await this.config.getConfiguration();
|
|
565
|
+
const response = await this.requestor.xhr({
|
|
566
|
+
url: config.registrationEndpoint,
|
|
567
|
+
method: 'POST',
|
|
568
|
+
dataType: 'json',
|
|
569
|
+
headers: {
|
|
570
|
+
'Content-Type': 'application/json',
|
|
571
|
+
Authorization: `Bearer ${token}`
|
|
572
|
+
}
|
|
573
|
+
// data: this._utils.stringify(map)
|
|
574
|
+
});
|
|
575
|
+
if (response.error === undefined) {
|
|
576
|
+
return new ClientRegistrationResponse(response);
|
|
577
|
+
}
|
|
578
|
+
else {
|
|
579
|
+
throw new AppAuthError(response.error);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
async getRegistrationCode(existingServicePrincipalId = null) {
|
|
583
|
+
const params = {
|
|
584
|
+
custom_action: 'sp_register',
|
|
585
|
+
service_principal_id: existingServicePrincipalId
|
|
586
|
+
};
|
|
587
|
+
return this.getDeviceCodeInternal(params);
|
|
588
|
+
}
|
|
589
|
+
async getDeviceCode(scope) {
|
|
590
|
+
const params = {
|
|
591
|
+
scope,
|
|
592
|
+
};
|
|
593
|
+
return this.getDeviceCodeInternal(params);
|
|
594
|
+
}
|
|
595
|
+
async getDeviceCodeInternal(params) {
|
|
596
|
+
const config = await this.config.getConfiguration();
|
|
597
|
+
params['client_id'] = this.config.clientId;
|
|
598
|
+
const map = params;
|
|
599
|
+
const response = await this.requestor.xhr({
|
|
600
|
+
url: config.deviceAuthorizationEndpoint,
|
|
601
|
+
method: 'POST',
|
|
602
|
+
dataType: 'json',
|
|
603
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
604
|
+
data: this._utils.stringify(map)
|
|
605
|
+
});
|
|
606
|
+
if (response.error === undefined) {
|
|
607
|
+
return new DeviceCode(response);
|
|
608
|
+
}
|
|
609
|
+
else {
|
|
610
|
+
throw new AppAuthError(response.error);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
TokenClient.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: TokenClient, deps: [{ token: AngularRequestor }, { token: OidcConfigurationService }], target: i0.ɵɵFactoryTarget.Injectable });
|
|
615
|
+
TokenClient.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: TokenClient, providedIn: 'root' });
|
|
616
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: TokenClient, decorators: [{
|
|
617
|
+
type: Injectable,
|
|
618
|
+
args: [{
|
|
619
|
+
providedIn: 'root'
|
|
620
|
+
}]
|
|
621
|
+
}], ctorParameters: function () { return [{ type: AngularRequestor }, { type: OidcConfigurationService }]; } });
|
|
622
|
+
|
|
623
|
+
class ServicePrincipal {
|
|
624
|
+
}
|
|
625
|
+
class ServicePrincipalRegistrationStatus {
|
|
626
|
+
constructor(servicePrincipal) {
|
|
627
|
+
this.isRegistered = false;
|
|
628
|
+
if (servicePrincipal) {
|
|
629
|
+
this.isRegistered = true;
|
|
630
|
+
this.id = servicePrincipal.id;
|
|
631
|
+
this.expiresAt = servicePrincipal.expiresAt;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
get isExpired() {
|
|
635
|
+
return false;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
class NucleusIdentityService {
|
|
640
|
+
constructor(appService, location, http, config, tokenClient) {
|
|
641
|
+
this.appService = appService;
|
|
642
|
+
this.http = http;
|
|
643
|
+
this.config = config;
|
|
644
|
+
this.tokenClient = tokenClient;
|
|
645
|
+
this._authorizationNotifier = new NucleusAuthorizationNotifier();
|
|
646
|
+
this._initStarted = false;
|
|
647
|
+
this._initialized = false;
|
|
648
|
+
this._servicePrincipalTokenId = '_svcp';
|
|
649
|
+
const storage = new LocalStorageBackend();
|
|
650
|
+
this._crypto = new NucleusCrypto();
|
|
651
|
+
this._authorizationHandler = new RedirectRequestHandler(storage, new BasicQueryStringUtils(), location, this._crypto);
|
|
652
|
+
this._authorizationHandler.setAuthorizationNotifier(this._authorizationNotifier);
|
|
653
|
+
this._store = new SecretsStore(config.clientId);
|
|
654
|
+
}
|
|
655
|
+
get identity() {
|
|
656
|
+
return this._store.getIdentity();
|
|
657
|
+
}
|
|
658
|
+
get isAuthenticated() {
|
|
659
|
+
return this.identity != null;
|
|
660
|
+
}
|
|
661
|
+
get servicePrincipalIdentity() {
|
|
662
|
+
return this._store.getIdentity(this._servicePrincipalTokenId);
|
|
663
|
+
}
|
|
664
|
+
get isServicePrincipalAuthenticated() {
|
|
665
|
+
return this.servicePrincipalIdentity != null;
|
|
666
|
+
}
|
|
667
|
+
async init(startLogin = false) {
|
|
668
|
+
if (this._initStarted || this._initialized) {
|
|
669
|
+
console.warn('Nucleus.Identity: Auth initialization was already started. Don\'t call init() multiple times!');
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
this._initStarted = true;
|
|
673
|
+
this.handleLaunchCodeHash();
|
|
674
|
+
await this._authorizationHandler.completeAuthorizationRequestIfPossible();
|
|
675
|
+
const authErr = this._authorizationNotifier.error;
|
|
676
|
+
if (authErr) {
|
|
677
|
+
throw new Error('Authorization err: ' + authErr.error + ': ' + authErr.errorDescription);
|
|
678
|
+
}
|
|
679
|
+
else if (this._authorizationNotifier.response) {
|
|
680
|
+
window.location.hash = '';
|
|
681
|
+
const request = this._authorizationNotifier.request;
|
|
682
|
+
const response = this._authorizationNotifier.response;
|
|
683
|
+
const res = await this.tokenClient.getByAuthorizationCode(request.redirectUri, response.code, request.internal['code_verifier']);
|
|
684
|
+
this._store.setDefaultIdentityId(null);
|
|
685
|
+
await this._store.setToken(res);
|
|
686
|
+
}
|
|
687
|
+
else {
|
|
688
|
+
const res = await this._store.getToken();
|
|
689
|
+
if (!res && startLogin) {
|
|
690
|
+
await this.login();
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
this._initialized = true;
|
|
694
|
+
}
|
|
695
|
+
async loginWithSecret(provider, secret) {
|
|
696
|
+
this._store.removeToken();
|
|
697
|
+
const assertionToken = await this.getServicePrincipalAccessToken();
|
|
698
|
+
const scope = this.prepareScope(true, this.config?.requestedScopes);
|
|
699
|
+
const res = await this.tokenClient.getBySecret(provider, secret, assertionToken, scope);
|
|
700
|
+
this._store.setDefaultIdentityId(null);
|
|
701
|
+
await this._store.setToken(res);
|
|
702
|
+
}
|
|
703
|
+
async login() {
|
|
704
|
+
this._store.removeToken();
|
|
705
|
+
const config = await this.config.getConfiguration();
|
|
706
|
+
const request = this.prepareAuthorizationRequest();
|
|
707
|
+
if (this.appService.isNative) {
|
|
708
|
+
const listener = App.addListener('appUrlOpen', data => {
|
|
709
|
+
if (this.appService.platform === 'ios') {
|
|
710
|
+
Browser.close();
|
|
711
|
+
}
|
|
712
|
+
listener.remove();
|
|
713
|
+
const hash = this.getCodeHash(data.url);
|
|
714
|
+
if (hash) {
|
|
715
|
+
const targetUrl = window.location.origin + window.location.pathname + '#' + hash;
|
|
716
|
+
window.location.assign(targetUrl);
|
|
717
|
+
window.location.reload();
|
|
718
|
+
}
|
|
719
|
+
else {
|
|
720
|
+
console.warn('Nucleus.Identity: Redirect url did not contain authorization code!', data);
|
|
721
|
+
}
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
this._authorizationHandler.performAuthorizationRequest(config, request);
|
|
725
|
+
}
|
|
726
|
+
async logout() {
|
|
727
|
+
this._store.removeToken();
|
|
728
|
+
const config = await this.config.getConfiguration();
|
|
729
|
+
const redirectUrl = this.config.redirectUrl;
|
|
730
|
+
const logoutUrl = config.endSessionEndpoint + '?post_logout_redirect_uri=' + encodeURI(redirectUrl);
|
|
731
|
+
if (this.appService.isNative) {
|
|
732
|
+
const listener = App.addListener('appUrlOpen', () => {
|
|
733
|
+
Device.getInfo().then(info => {
|
|
734
|
+
if (info.platform === 'ios') {
|
|
735
|
+
Browser.close();
|
|
736
|
+
}
|
|
737
|
+
});
|
|
738
|
+
listener.remove();
|
|
739
|
+
});
|
|
740
|
+
Browser.open({ url: logoutUrl });
|
|
741
|
+
}
|
|
742
|
+
else {
|
|
743
|
+
window.location.assign(logoutUrl);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
async getAccessToken() {
|
|
747
|
+
if (!this._getTokenPromise) {
|
|
748
|
+
this._getTokenPromise = this.getAccessTokenInternal();
|
|
749
|
+
}
|
|
750
|
+
try {
|
|
751
|
+
return await this._getTokenPromise;
|
|
752
|
+
}
|
|
753
|
+
finally {
|
|
754
|
+
this._getTokenPromise = null;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
async getServicePrincipalAccessToken() {
|
|
758
|
+
if (!this._getServicePrincipalTokenPromise) {
|
|
759
|
+
this._getServicePrincipalTokenPromise = this.getServicePrincipalAccessTokenInternal();
|
|
760
|
+
}
|
|
761
|
+
try {
|
|
762
|
+
return await this._getServicePrincipalTokenPromise;
|
|
763
|
+
}
|
|
764
|
+
finally {
|
|
765
|
+
this._getServicePrincipalTokenPromise = null;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
async loginServicePrincipal() {
|
|
769
|
+
const sp = await this._store.getServicePrincipal();
|
|
770
|
+
if (sp) {
|
|
771
|
+
const scope = this.prepareScope(false, this.config.servicePrincipalRequestedScopes);
|
|
772
|
+
const res = await this.tokenClient.getByClientCredentials(sp.id, sp.secret, scope);
|
|
773
|
+
await this._store.setToken(res, this._servicePrincipalTokenId);
|
|
774
|
+
return res;
|
|
775
|
+
}
|
|
776
|
+
else {
|
|
777
|
+
throw Error('Service principal is not registered!');
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
async loginAsServicePrincipal() {
|
|
781
|
+
const token = await this._store.getToken(this._servicePrincipalTokenId);
|
|
782
|
+
if (!token) {
|
|
783
|
+
await this.loginServicePrincipal();
|
|
784
|
+
}
|
|
785
|
+
this._store.setDefaultIdentityId(this._servicePrincipalTokenId);
|
|
786
|
+
}
|
|
787
|
+
async getOtp(type, expiresIn = -1) {
|
|
788
|
+
let url = this.config.getServerUrl(`/otp/create?type=${type}`);
|
|
789
|
+
if (expiresIn > 0) {
|
|
790
|
+
url += `&expiresIn=${expiresIn}`;
|
|
791
|
+
}
|
|
792
|
+
return lastValueFrom(this.http.get(url));
|
|
793
|
+
}
|
|
794
|
+
async getOtpStatus(id) {
|
|
795
|
+
const url = this.config.getServerUrl(`/otp/status/${id}`);
|
|
796
|
+
return lastValueFrom(this.http.get(url));
|
|
797
|
+
}
|
|
798
|
+
getOtpUrl(redirectUrl, password) {
|
|
799
|
+
const encoded = encodeURIComponent(redirectUrl);
|
|
800
|
+
const url = `/otp/auth?otpValue=${password}&returnUrl=${encoded}`;
|
|
801
|
+
return this.config.getServerUrl(url);
|
|
802
|
+
}
|
|
803
|
+
async startServicePrincipalRegistration() {
|
|
804
|
+
const sp = await this._store.getServicePrincipal();
|
|
805
|
+
return await this.tokenClient.getRegistrationCode(sp?.id);
|
|
806
|
+
}
|
|
807
|
+
async completeServicePrincipalRegistration(deviceCode) {
|
|
808
|
+
const tokenRes = await this.waitForDeviceToken(deviceCode);
|
|
809
|
+
const regRes = await this.tokenClient.registerServicePrincipal(tokenRes.accessToken);
|
|
810
|
+
await this._store.setServicePrincipal({
|
|
811
|
+
id: regRes.clientId,
|
|
812
|
+
secret: regRes.clientSecret,
|
|
813
|
+
expiresAt: regRes.secretExpirationDate
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
removeServicePrincipalRegistration() {
|
|
817
|
+
return this._store.removeServicePrincipal();
|
|
818
|
+
}
|
|
819
|
+
async getServicePrincipalRegistrationStatus() {
|
|
820
|
+
const sp = await this._store.getServicePrincipal();
|
|
821
|
+
return new ServicePrincipalRegistrationStatus(sp);
|
|
822
|
+
}
|
|
823
|
+
async startDeviceCodeLogin() {
|
|
824
|
+
const scope = this.prepareScope(true, this.config.requestedScopes);
|
|
825
|
+
return await this.tokenClient.getDeviceCode(scope);
|
|
826
|
+
}
|
|
827
|
+
async completeDeviceCodeLogin(deviceCode) {
|
|
828
|
+
const res = await this.waitForDeviceToken(deviceCode);
|
|
829
|
+
await this._store.setToken(res);
|
|
830
|
+
}
|
|
831
|
+
async waitForDeviceToken(deviceCode) {
|
|
832
|
+
let res = null;
|
|
833
|
+
do {
|
|
834
|
+
if (deviceCode.isExpired()) {
|
|
835
|
+
throw Error('Device code is expired!');
|
|
836
|
+
}
|
|
837
|
+
try {
|
|
838
|
+
res = await this.tokenClient.getByDeviceCode(deviceCode.deviceCode);
|
|
839
|
+
}
|
|
840
|
+
catch (error) {
|
|
841
|
+
if (error instanceof AppAuthError && error.message === 'authorization_pending') {
|
|
842
|
+
await this.delay(2000);
|
|
843
|
+
}
|
|
844
|
+
else {
|
|
845
|
+
throw error;
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
} while (!res);
|
|
849
|
+
return res;
|
|
850
|
+
}
|
|
851
|
+
prepareAuthorizationRequest() {
|
|
852
|
+
const redirectUri = this.config.redirectUrl;
|
|
853
|
+
const params = {
|
|
854
|
+
response_mode: 'fragment',
|
|
855
|
+
prompt: 'consent',
|
|
856
|
+
access_type: 'offline',
|
|
857
|
+
auth_provider_hint: this.config.authProviderHint
|
|
858
|
+
};
|
|
859
|
+
return new AuthorizationRequest({
|
|
860
|
+
client_id: this.config.clientId,
|
|
861
|
+
redirect_uri: redirectUri,
|
|
862
|
+
response_type: AuthorizationRequest.RESPONSE_TYPE_CODE,
|
|
863
|
+
scope: this.prepareScope(true, this.config.requestedScopes),
|
|
864
|
+
extras: params,
|
|
865
|
+
}, this._crypto, true);
|
|
866
|
+
}
|
|
867
|
+
async getServicePrincipalAccessTokenInternal() {
|
|
868
|
+
let token = await this._store.getToken(this._servicePrincipalTokenId);
|
|
869
|
+
if (!token?.isValid()) {
|
|
870
|
+
token = await this.loginServicePrincipal();
|
|
871
|
+
}
|
|
872
|
+
return token?.accessToken;
|
|
873
|
+
}
|
|
874
|
+
async getAccessTokenInternal() {
|
|
875
|
+
let token = await this._store.getToken();
|
|
876
|
+
if (token && !token.isValid()) {
|
|
877
|
+
token = await this.loginWithRefreshToken(token);
|
|
878
|
+
}
|
|
879
|
+
return token?.accessToken;
|
|
880
|
+
}
|
|
881
|
+
async loginWithRefreshToken(token) {
|
|
882
|
+
if (!this._refreshTokenPromise) {
|
|
883
|
+
this._refreshTokenPromise = this.loginWithRefreshTokenInternal(token);
|
|
884
|
+
}
|
|
885
|
+
try {
|
|
886
|
+
return await this._refreshTokenPromise;
|
|
887
|
+
}
|
|
888
|
+
finally {
|
|
889
|
+
this._refreshTokenPromise = null;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
async loginWithRefreshTokenInternal(token) {
|
|
893
|
+
if (token?.refreshToken) {
|
|
894
|
+
try {
|
|
895
|
+
const res = await this.tokenClient.getByRefreshToken(token.refreshToken);
|
|
896
|
+
await this._store.setToken(res);
|
|
897
|
+
return res;
|
|
898
|
+
}
|
|
899
|
+
catch (err) {
|
|
900
|
+
console.warn('Nucleus.Identity: Failed to login with refresh token.', err);
|
|
901
|
+
if (err.message === 'invalid_grant') {
|
|
902
|
+
await this.logout();
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
else {
|
|
907
|
+
console.warn('Nucleus.Identity: There is no refresh token available.');
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
getCodeHash(url) {
|
|
911
|
+
const arr = url.split('#');
|
|
912
|
+
if (arr.length > 1) {
|
|
913
|
+
const hash = arr[1];
|
|
914
|
+
if (hash.startsWith('code=')) {
|
|
915
|
+
return hash;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
return null;
|
|
919
|
+
}
|
|
920
|
+
handleLaunchCodeHash() {
|
|
921
|
+
if (this.appService.isNative && this.appService.launchUrl) {
|
|
922
|
+
const hash = this.getCodeHash(this.appService.launchUrl);
|
|
923
|
+
if (hash) {
|
|
924
|
+
console.log('Nucleus.Identity: Got authorization code from launchUrl, will assign it to hash.');
|
|
925
|
+
window.location.hash = '#' + hash;
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
prepareScope(offlineAccess, aditionalScope) {
|
|
930
|
+
let scope = 'openid';
|
|
931
|
+
if (offlineAccess) {
|
|
932
|
+
scope += ' offline_access';
|
|
933
|
+
}
|
|
934
|
+
if (scope) {
|
|
935
|
+
scope += ' ' + aditionalScope;
|
|
936
|
+
}
|
|
937
|
+
return scope;
|
|
938
|
+
}
|
|
939
|
+
delay(miliseconds) {
|
|
940
|
+
return new Promise(resolve => {
|
|
941
|
+
setTimeout(() => {
|
|
942
|
+
resolve();
|
|
943
|
+
}, miliseconds);
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
NucleusIdentityService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: NucleusIdentityService, deps: [{ token: i1.NucleusAppService }, { token: LocationService }, { token: i1$1.HttpClient }, { token: OidcConfigurationService }, { token: TokenClient }], target: i0.ɵɵFactoryTarget.Injectable });
|
|
948
|
+
NucleusIdentityService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: NucleusIdentityService, providedIn: 'root' });
|
|
949
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: NucleusIdentityService, decorators: [{
|
|
950
|
+
type: Injectable,
|
|
951
|
+
args: [{
|
|
952
|
+
providedIn: 'root'
|
|
953
|
+
}]
|
|
954
|
+
}], ctorParameters: function () { return [{ type: i1.NucleusAppService }, { type: LocationService }, { type: i1$1.HttpClient }, { type: OidcConfigurationService }, { type: TokenClient }]; } });
|
|
955
|
+
|
|
956
|
+
class NucleusTokenInterceptor {
|
|
957
|
+
constructor(auth, config) {
|
|
958
|
+
this.auth = auth;
|
|
959
|
+
this.config = config;
|
|
960
|
+
this._authorityInterceptPaths = ['/api', '/manage', '/otp/create', '/otp/status'];
|
|
961
|
+
this._authority = config.authority.toLowerCase();
|
|
962
|
+
this._interceptUrls = config.httpInterceptorUrls?.map(x => x.toLowerCase());
|
|
963
|
+
}
|
|
964
|
+
intercept(req, next) {
|
|
965
|
+
if (this.shouldIntercept(req.url)) {
|
|
966
|
+
const res = this.authorizeRequest(this.auth.getAccessToken(), req, next);
|
|
967
|
+
return this.checkUnauthorized(res);
|
|
968
|
+
}
|
|
969
|
+
return next.handle(req);
|
|
970
|
+
}
|
|
971
|
+
shouldIntercept(url) {
|
|
972
|
+
url = url.toLowerCase();
|
|
973
|
+
if (url.startsWith(this._authority)) {
|
|
974
|
+
const pathname = new URL(url).pathname;
|
|
975
|
+
return (this._authorityInterceptPaths.some(x => pathname.startsWith(x)));
|
|
976
|
+
}
|
|
977
|
+
if (this._interceptUrls?.length > 0) {
|
|
978
|
+
return this.config.httpInterceptorUrls.some(x => url.startsWith(x));
|
|
979
|
+
}
|
|
980
|
+
return false;
|
|
981
|
+
}
|
|
982
|
+
authorizeRequest(getToken, req, next) {
|
|
983
|
+
return from(getToken).pipe(mergeMap(token => {
|
|
984
|
+
if (token) {
|
|
985
|
+
const headers = req.headers.set('Authorization', `Bearer ${token}`);
|
|
986
|
+
req = req.clone({ headers });
|
|
987
|
+
}
|
|
988
|
+
return next.handle(req);
|
|
989
|
+
}));
|
|
990
|
+
}
|
|
991
|
+
checkUnauthorized(response) {
|
|
992
|
+
return response.pipe(catchError((err) => {
|
|
993
|
+
if (err instanceof HttpErrorResponse && err.status === 401) {
|
|
994
|
+
if (this.config.automaticLoginOnHttp401) {
|
|
995
|
+
this.auth.login();
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
return throwError(err);
|
|
999
|
+
}));
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
NucleusTokenInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: NucleusTokenInterceptor, deps: [{ token: NucleusIdentityService }, { token: NucleusIdentityConfig }], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1003
|
+
NucleusTokenInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: NucleusTokenInterceptor, providedIn: 'root' });
|
|
1004
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: NucleusTokenInterceptor, decorators: [{
|
|
1005
|
+
type: Injectable,
|
|
1006
|
+
args: [{
|
|
1007
|
+
providedIn: 'root'
|
|
1008
|
+
}]
|
|
1009
|
+
}], ctorParameters: function () { return [{ type: NucleusIdentityService }, { type: NucleusIdentityConfig }]; } });
|
|
1010
|
+
|
|
1011
|
+
class NucleusIdentityModule {
|
|
1012
|
+
static forRoot(config) {
|
|
1013
|
+
return {
|
|
1014
|
+
ngModule: NucleusIdentityModule,
|
|
1015
|
+
providers: [
|
|
1016
|
+
{ provide: NucleusIdentityConfig, useValue: config },
|
|
1017
|
+
{ provide: HTTP_INTERCEPTORS, useClass: NucleusTokenInterceptor, multi: true },
|
|
1018
|
+
]
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
NucleusIdentityModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: NucleusIdentityModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
|
|
1023
|
+
NucleusIdentityModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: NucleusIdentityModule });
|
|
1024
|
+
NucleusIdentityModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: NucleusIdentityModule, imports: [[]] });
|
|
1025
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: NucleusIdentityModule, decorators: [{
|
|
1026
|
+
type: NgModule,
|
|
1027
|
+
args: [{
|
|
1028
|
+
imports: [],
|
|
1029
|
+
declarations: [],
|
|
1030
|
+
exports: []
|
|
1031
|
+
}]
|
|
1032
|
+
}] });
|
|
1033
|
+
|
|
1034
|
+
class OtpResponse {
|
|
1035
|
+
}
|
|
1036
|
+
class OtpStatus {
|
|
1037
|
+
}
|
|
1038
|
+
var OtpType;
|
|
1039
|
+
(function (OtpType) {
|
|
1040
|
+
OtpType[OtpType["SimpleNumbers"] = 0] = "SimpleNumbers";
|
|
1041
|
+
OtpType[OtpType["SimpleAlfanumeric"] = 1] = "SimpleAlfanumeric";
|
|
1042
|
+
OtpType[OtpType["Complex"] = 2] = "Complex";
|
|
1043
|
+
})(OtpType || (OtpType = {}));
|
|
1044
|
+
|
|
1045
|
+
/*
|
|
1046
|
+
* Public API Surface of nucleus-identity
|
|
1047
|
+
*/
|
|
1048
|
+
|
|
1049
|
+
/**
|
|
1050
|
+
* Generated bundle index. Do not edit.
|
|
1051
|
+
*/
|
|
1052
|
+
|
|
1053
|
+
export { DeviceCode, Identity, NucleusIdentityConfig, NucleusIdentityModule, NucleusIdentityService, OtpResponse, OtpStatus, OtpType, ServicePrincipalRegistrationStatus };
|
|
1054
|
+
//# sourceMappingURL=kolektor-nucleus-identity.mjs.map
|