forked from michaelschnyder/oidc-angular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoidc-angular.js
More file actions
554 lines (414 loc) · 18.6 KB
/
oidc-angular.js
File metadata and controls
554 lines (414 loc) · 18.6 KB
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
'use strict';
(function() {
var eventPrefix = 'oidcauth:';
var unauthorizedEvent = eventPrefix + 'unauthorized';
var tokenExpiredEvent = eventPrefix + 'tokenExpired';
var tokenMissingEvent = eventPrefix + 'tokenMissing';
var tokenExpiresSoonEvent = eventPrefix + 'tokenExpires';
var loggedInEvent = eventPrefix + 'loggedIn';
var loggedOutEvent = eventPrefix + 'loggedOut';
var silentRefreshStartedEvent = eventPrefix + 'silentRefreshStarted';
var silentRefreshSuceededEvent = eventPrefix + 'silentRefreshSucceded';
var silentRefreshFailedEvent = eventPrefix + 'silentRefreshFailed';
var silentRefreshTimeoutEvent = eventPrefix + 'silentRefreshTimeout';
// Module registrarion
var oidcmodule = angular.module('oidc-angular', ['base64', 'ngStorage', 'ngRoute']);
oidcmodule.config(['$httpProvider', '$routeProvider', function($httpProvider, $routeProvider) {
$httpProvider.interceptors.push('oidcHttpInterceptor');
// Register callback route
$routeProvider.
when('/auth/callback/:data', {
template: '',
controller: ['$auth', '$routeParams', function ($auth, $routeParams) {
console.debug('oidc-angular: handling login-callback');
$auth.handleSignInCallback($routeParams.data);
}]
}).
when('/auth/clear', {
template: '',
controller: ['$auth', function ($auth) {
console.debug('oidc-angular: handling logout-callback');
$auth.handleSignOutCallback();
}]
});
console.debug('oidc-angular: callback routes registered.')
}]);
oidcmodule.factory('oidcHttpInterceptor', ['$rootScope', '$q', '$auth', 'tokenService', function($rootScope, $q, $auth, tokenService) {
return {
'request': function(request) {
if (request.url.startsWith($auth.config.apiUrl)) {
var appendBearer = false;
if($auth.config.enableRequestChecks) {
// Only append token when it's valid.
if (tokenService.hasToken()) {
if (tokenService.hasValidToken())
{
appendBearer = true;
}
else {
$rootScope.$broadcast(tokenExpiredEvent, { request: request });
}
}
else {
$rootScope.$broadcast(tokenMissingEvent, { request: request });
}
}
else {
appendBearer = tokenService.hasToken();
}
if (appendBearer) {
var token = tokenService.getIdToken();
request.headers['Authorization'] = 'Bearer ' + token;
}
}
// do something on success
return request;
},
'response': function(response) {
// Proactively check if the token will expire soon
$auth.validateExpirity();
return response;
},
'responseError': function(response) {
if (response.status == 401) {
if (!tokenService.hasToken()) {
// There was probably no token attached, because there is none
$rootScope.$broadcast(tokenMissingEvent, { response: response });
}
else if (!tokenService.hasValidToken()) {
// Seems the token is not valid anymore
$rootScope.$broadcast(tokenExpiredEvent, { response: response });
}
else {
// any other
$rootScope.$broadcast(unauthorizedEvent, { response: response });
}
}
return $q.reject(response);
}
};
}]);
oidcmodule.service('tokenService', ['$base64', '$localStorage', function ($base64, $localStorage) {
var service = this;
var sanitize = function (base64data) {
// Pad lenght to comply with the standard
while (base64data.length % 4 !== 0) {
base64data += "=";
}
// convert to base64 from base64url
base64data = base64data.replace('_', '/');
base64data = base64data.replace('-', '+');
return base64data;
};
service.getPayloadFromRawToken = function(raw)
{
var tokenParts = raw.split(".");
return tokenParts[1];
};
service.deserializeClaims = function(raw) {
var claimsBase64 = sanitize(raw);
var claimsJson = $base64.decode(claimsBase64);
var claims = JSON.parse(claimsJson);
return claims;
};
service.convertToClaims = function(id_token) {
var payload = service.getPayloadFromRawToken(id_token);
var claims = service.deserializeClaims(payload);
return claims;
};
service.saveToken = function (id_token) {
$localStorage['idToken'] = id_token;
var idClaims = service.convertToClaims(id_token);
$localStorage['cached-claims'] = idClaims;
};
service.hasToken = function() {
var claims = service.allClaims();
if (!(claims && claims.hasOwnProperty("iat") && claims.hasOwnProperty('exp'))) {
return false;
}
return true;
};
service.hasValidToken = function() {
if (!this.hasToken()) return false;
var claims = service.allClaims();
var now = Date.now();
var issuedAtMSec = claims.iat * 1000;
var expiresAtMSec = claims.exp * 1000;
var marginMSec = 1000 * 60 * 5; // 5 Minutes
// Substract margin, because browser time could be a bit in the past
if (issuedAtMSec - marginMSec > now) {
console.log('oidc-connect: Token is not yet valid!')
return false
}
if (expiresAtMSec < now) {
console.log('oidc-connect: Token has expired!')
return false;
}
return true;
}
service.allClaims = function() {
var cachedClaims = $localStorage['cached-claims'];
if (!cachedClaims) {
var id_token = service.getIdToken();
if (id_token) {
var claims = service.convertToClaims(id_token);
var idClaims = service.convertToClaims(id_token);
$localStorage['cached-claims'] = idClaims;
return claims;
}
}
return cachedClaims;
};
service.getIdToken = function() {
return $localStorage['idToken'];
};
service.clearTokens = function() {
delete $localStorage['cached-claims'];
delete $localStorage['idToken'];
}
}]);
oidcmodule.provider("$auth", ['$routeProvider', function ($routeProvider) {
// Default configuration
var config = {
basePath: null,
clientId: null,
apiUrl: '/api/',
responseType: 'id_token',
scope: "openid profile",
redirectUri: (window.location.origin || window.location.protocol + '//' + window.location.host) + window.location.pathname + '#/auth/callback/',
logoutUri: (window.location.origin || window.location.protocol + '//' + window.location.host) + window.location.pathname + '#/auth/clear',
state: "",
authorizationEndpoint: 'connect/authorize',
revocationEndpoint: 'connect/revocation',
endSessionEndpoint: 'connect/endsession',
advanceRefresh: 300,
enableRequestChecks: false,
stickToLastKnownIdp: false
};
return {
// Service configuration
configure: function (params) {
angular.extend(config, params);
},
// Service itself
$get: ['$q', '$document', '$rootScope', '$localStorage', '$location', 'tokenService', function ($q, $document, $rootScope, $localStorage, $location, tokenService) {
var init = function() {
if ($localStorage['logoutActive']) {
delete $localStorage['logoutActive'];
tokenService.clearTokens();
}
if ($localStorage['refreshRunning']) {
delete $localStorage['refreshRunning'];
}
};
var createLoginUrl = function (nonce, state) {
var hasPathDelimiter = config.basePath.endsWith('/');
var appendChar = (hasPathDelimiter) ? '' : '/';
var currentClaims = tokenService.allClaims();
if (currentClaims) {
var idpClaimValue = currentClaims["idp"];
}
var baseUrl = config.basePath + appendChar;
var url = baseUrl + config.authorizationEndpoint
+ "?response_type="
+ encodeURIComponent(config.responseType)
+ "&client_id="
+ encodeURIComponent(config.clientId)
+ "&state="
+ encodeURIComponent(state || config.state)
+ "&redirect_uri="
+ encodeURIComponent(config.redirectUri)
+ "&scope="
+ encodeURIComponent(config.scope)
+ "&nonce="
+ encodeURIComponent(nonce);
if (config.stickToLastKnownIdp && idpClaimValue) {
url = url + "&acr_values="
+ encodeURIComponent("idp:" + idpClaimValue);
}
return url;
};
var createLogoutUrl = function(state) {
var idToken = tokenService.getIdToken();
var hasPathDelimiter = config.basePath.endsWith('/');
var appendChar = (hasPathDelimiter) ? '' : '/';
var baseUrl = config.basePath + appendChar;
var url = baseUrl + config.endSessionEndpoint
+ "?id_token_hint="
+ encodeURIComponent(idToken)
+ "&post_logout_redirect_uri="
+ encodeURIComponent(config.logoutUri)
+ "&state="
+ encodeURIComponent(state || config.state)
+ "&r=" + Math.random();
return url;
}
var startImplicitFlow = function (localRedirect) {
$localStorage['localRedirect'] = localRedirect;
var url = createLoginUrl("dummynonce");
window.location.replace(url);
};
var startLogout = function () {
var url = createLogoutUrl();
$localStorage['logoutActive'] = true;
window.location.replace(url);
};
var handleImplicitFlowCallback = function(id_token) {
tokenService.saveToken(id_token);
var localRedirect = $localStorage['localRedirect'];
if (localRedirect) {
var redirectTo = localRedirect.hash.substring(1);
delete $localStorage['localRedirect'];
$location.path(redirectTo);
}
else {
$location.path('/');
}
$rootScope.$broadcast(loggedInEvent);
return true;
};
var handleSilentRefreshCallback = function(newIdToken) {
delete $localStorage['refreshRunning'];
var currentIdToken = tokenService.getIdToken();
var currentClaims = tokenService.allClaims();
var newClaims = tokenService.convertToClaims(newIdToken)
if (currentClaims.exp && newClaims.exp && newClaims.exp > currentClaims.exp) {
tokenService.saveToken(newIdToken);
$rootScope.$broadcast(silentRefreshSuceededEvent);
}
else {
$rootScope.$broadcast(silentRefreshFailedEvent);
}
};
var trySilentRefresh = function() {
if ($localStorage['refreshRunning']) {
return;
}
$localStorage['refreshRunning'] = true;
$rootScope.$broadcast(silentRefreshStartedEvent);
var url = createLoginUrl('dummynonce', 'refresh');
var html = "<iframe src='" + url + "' height='400' width='100%' id='oauthFrame' style='display:none;visibility:hidden;'></iframe>";
var elem = angular.element(html);
$document.find("body").append(elem);
setTimeout(function() {
if ($localStorage['refreshRunning']) {
$rootScope.$broadcast(silentRefreshTimeoutEvent);
delete $localStorage['refreshRunning']
}
$document.find("#oauthFrame").remove();
}, 5000);
};
var handleSignInCallback = function(data) {
if (!data && window.location.hash.indexOf("#") === 0) {
data = window.location.hash.substr(16)
}
var fragments = {}
if (data) {
fragments = parseQueryString(data);
}
else {
throw Error("Unable to process callback. No data given!");
}
console.debug("oidc-angular: Processing callback information", data);
var id_token = fragments['id_token'];
var state = fragments['state'];
if (id_token) {
if (state === 'refresh') {
handleSilentRefreshCallback(id_token);
}
else {
handleImplicitFlowCallback(id_token);
}
}
};
var handleSignOutCallback = function() {
delete $localStorage['logoutActive'];
tokenService.clearTokens();
$location.path('/');
$rootScope.$broadcast(loggedOutEvent);
};
var tokenIsValidAt = function(date) {
var claims = tokenService.allClaims();
var expiresAtMSec = claims.exp * 1000;
if (date <= expiresAtMSec) {
return true;
}
return false;
}
var validateExpirity = function() {
if (!tokenService.hasToken()) return;
if (!tokenService.hasValidToken()) return;
var now = Date.now();
if (!tokenIsValidAt(now + config.advanceRefresh)) {
$rootScope.$broadcast(tokenExpiresSoonEvent);
trySilentRefresh();
}
};
init();
return {
config: config,
handleSignInCallback : handleSignInCallback,
handleSignOutCallback : handleSignOutCallback,
validateExpirity: validateExpirity,
isAuthenticated : function() {
return tokenService.hasValidToken();
},
isAuthenticatedIn : function(milliseconds) {
return tokenService.hasValidToken() && tokenIsValidAt(new Date().getTime() + milliseconds);
},
signIn : function(localRedirect) {
startImplicitFlow(localRedirect);
},
signOut : function() {
startLogout();
},
silentRefresh : function() {
trySilentRefresh();
}
};
}]
};
}]);
/* Helpers & Polyfills */
function parseQueryString(queryString) {
var data = {}, pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;
if (queryString === null) {
return data;
}
pairs = queryString.split("&");
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
separatorIndex = pair.indexOf("=");
if (separatorIndex === -1) {
escapedKey = pair;
escapedValue = null;
} else {
escapedKey = pair.substr(0, separatorIndex);
escapedValue = pair.substr(separatorIndex + 1);
}
key = decodeURIComponent(escapedKey);
value = decodeURIComponent(escapedValue);
if (key.substr(0, 1) === '/')
key = key.substr(1);
data[key] = value;
}
return data;
};
if (!String.prototype.endsWith) {
String.prototype.endsWith = function (searchString, position) {
var subjectString = this.toString();
if (position === undefined || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
};
}
})();