keycloak-angular
Version:
Easy Keycloak setup for Angular applications
1,064 lines (1,058 loc) • 136 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common/http'), require('keycloak-js'), require('rxjs'), require('rxjs/operators'), require('@angular/common')) :
typeof define === 'function' && define.amd ? define('keycloak-angular', ['exports', '@angular/core', '@angular/common/http', 'keycloak-js', 'rxjs', 'rxjs/operators', '@angular/common'], factory) :
(factory((global['keycloak-angular'] = {}),global.ng.core,global.ng.common.http,global.Keycloak,global.rxjs,global.rxjs.operators,global.ng.common));
}(this, (function (exports,core,http,Keycloak_,rxjs,operators,common) { 'use strict';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Mauricio Gemelli Vigolo and contributors.
*
* Use of this source code is governed by a MIT-style license that can be
* found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/LICENSE
*/
/** @enum {number} */
var KeycloakEventType = {
/**
* Called if there was an error during authentication.
*/
OnAuthError: 0,
/**
* Called if the user is logged out
* (will only be called if the session status iframe is enabled, or in Cordova mode).
*/
OnAuthLogout: 1,
/**
* Called if there was an error while trying to refresh the token.
*/
OnAuthRefreshError: 2,
/**
* Called when the token is refreshed.
*/
OnAuthRefreshSuccess: 3,
/**
* Called when a user is successfully authenticated.
*/
OnAuthSuccess: 4,
/**
* Called when the adapter is initialized.
*/
OnReady: 5,
/**
* Called when the access token is expired. If a refresh token is available the token
* can be refreshed with updateToken, or in cases where it is not (that is, with implicit flow)
* you can redirect to login screen to obtain a new access token.
*/
OnTokenExpired: 6,
};
KeycloakEventType[KeycloakEventType.OnAuthError] = 'OnAuthError';
KeycloakEventType[KeycloakEventType.OnAuthLogout] = 'OnAuthLogout';
KeycloakEventType[KeycloakEventType.OnAuthRefreshError] = 'OnAuthRefreshError';
KeycloakEventType[KeycloakEventType.OnAuthRefreshSuccess] = 'OnAuthRefreshSuccess';
KeycloakEventType[KeycloakEventType.OnAuthSuccess] = 'OnAuthSuccess';
KeycloakEventType[KeycloakEventType.OnReady] = 'OnReady';
KeycloakEventType[KeycloakEventType.OnTokenExpired] = 'OnTokenExpired';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try {
step(generator.next(value));
}
catch (e) {
reject(e);
} }
function rejected(value) { try {
step(generator["throw"](value));
}
catch (e) {
reject(e);
} }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function () { if (t[0] & 1)
throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
return t;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
}
catch (e) {
op = [6, e];
y = 0;
}
finally {
f = t = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
}
catch (error) {
e = { error: error };
}
finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
}
finally {
if (e)
throw e.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* A simple guard implementation out of the box. This class should be inherited and
* implemented by the application. The only method that should be implemented is #isAccessAllowed.
* The reason for this is that the authorization flow is usually not unique, so in this way you will
* have more freedom to customize your authorization flow.
* @abstract
*/
var /**
* A simple guard implementation out of the box. This class should be inherited and
* implemented by the application. The only method that should be implemented is #isAccessAllowed.
* The reason for this is that the authorization flow is usually not unique, so in this way you will
* have more freedom to customize your authorization flow.
* @abstract
*/ KeycloakAuthGuard = (function () {
function KeycloakAuthGuard(router, keycloakAngular) {
this.router = router;
this.keycloakAngular = keycloakAngular;
}
/**
* CanActivate checks if the user is logged in and get the full list of roles (REALM + CLIENT)
* of the logged user. This values are set to authenticated and roles params.
*
* @param route
* @param state
*/
/**
* CanActivate checks if the user is logged in and get the full list of roles (REALM + CLIENT)
* of the logged user. This values are set to authenticated and roles params.
*
* @param {?} route
* @param {?} state
* @return {?}
*/
KeycloakAuthGuard.prototype.canActivate = /**
* CanActivate checks if the user is logged in and get the full list of roles (REALM + CLIENT)
* of the logged user. This values are set to authenticated and roles params.
*
* @param {?} route
* @param {?} state
* @return {?}
*/
function (route, state) {
var _this = this;
return new Promise(function (resolve, reject) {
return __awaiter(_this, void 0, void 0, function () {
var _a, _b, result, error_1;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_c.trys.push([0, 4, , 5]);
_a = this;
return [4 /*yield*/, this.keycloakAngular.isLoggedIn()];
case 1:
_a.authenticated = _c.sent();
_b = this;
return [4 /*yield*/, this.keycloakAngular.getUserRoles(true)];
case 2:
_b.roles = _c.sent();
return [4 /*yield*/, this.isAccessAllowed(route, state)];
case 3:
result = _c.sent();
resolve(result);
return [3 /*break*/, 5];
case 4:
error_1 = _c.sent();
reject('An error happened during access validation. Details:' + error_1);
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
});
});
};
return KeycloakAuthGuard;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/** @type {?} */
var Keycloak = Keycloak_;
/**
* Service to expose existent methods from the Keycloak JS adapter, adding new
* functionalities to improve the use of keycloak in Angular v > 4.3 applications.
*
* This class should be injected in the application bootstrap, so the same instance will be used
* along the web application.
*/
var KeycloakService = (function () {
function KeycloakService() {
this._keycloakEvents$ = new rxjs.Subject();
}
/**
* Sanitizes the bearer prefix, preparing it to be appended to
* the token.
*
* @param {?} bearerPrefix
* Prefix to be appended to the authorization header as
* Authorization: <bearer-prefix> <token>.
* @return {?}
* The bearer prefix sanitized, meaning that it will follow the bearerPrefix
* param as described in the library initilization or the default value bearer,
* with a space append in the end for the token concatenation.
*/
KeycloakService.prototype.sanitizeBearerPrefix = /**
* Sanitizes the bearer prefix, preparing it to be appended to
* the token.
*
* @param {?} bearerPrefix
* Prefix to be appended to the authorization header as
* Authorization: <bearer-prefix> <token>.
* @return {?}
* The bearer prefix sanitized, meaning that it will follow the bearerPrefix
* param as described in the library initilization or the default value bearer,
* with a space append in the end for the token concatenation.
*/
function (bearerPrefix) {
/** @type {?} */
var prefix = (bearerPrefix || 'bearer').trim();
return prefix.concat(' ');
};
/**
* Sets default value to true if it is undefined or null.
*
* @param {?} value - boolean value to be checked
* @return {?}
*/
KeycloakService.prototype.ifUndefinedIsTrue = /**
* Sets default value to true if it is undefined or null.
*
* @param {?} value - boolean value to be checked
* @return {?}
*/
function (value) {
/** @type {?} */
var returnValue = value;
if (returnValue === undefined || returnValue === null) {
returnValue = true;
}
return returnValue;
};
/**
* Binds the keycloak-js events to the keycloakEvents Subject
* which is a good way to monitor for changes, if needed.
*
* The keycloakEvents returns the keycloak-js event type and any
* argument if the source function provides any.
* @return {?}
*/
KeycloakService.prototype.bindsKeycloakEvents = /**
* Binds the keycloak-js events to the keycloakEvents Subject
* which is a good way to monitor for changes, if needed.
*
* The keycloakEvents returns the keycloak-js event type and any
* argument if the source function provides any.
* @return {?}
*/
function () {
var _this = this;
if (!this._instance) {
console.warn('Keycloak Angular events could not be registered as the keycloak instance is undefined.');
return;
}
this._instance.onAuthError = function (errorData) {
_this._keycloakEvents$.next({ args: errorData, type: KeycloakEventType.OnAuthError });
};
this._instance.onAuthLogout = function () {
_this._keycloakEvents$.next({ type: KeycloakEventType.OnAuthLogout });
};
this._instance.onAuthRefreshError = function () {
_this._keycloakEvents$.next({ type: KeycloakEventType.OnAuthRefreshError });
};
this._instance.onAuthSuccess = function () {
_this._keycloakEvents$.next({ type: KeycloakEventType.OnAuthSuccess });
};
this._instance.onTokenExpired = function () {
_this._keycloakEvents$.next({ type: KeycloakEventType.OnTokenExpired });
};
this._instance.onReady = function (authenticated) {
_this._keycloakEvents$.next({ args: authenticated, type: KeycloakEventType.OnReady });
};
};
/**
* Keycloak initialization. It should be called to initialize the adapter.
* Options is a object with 2 main parameters: config and initOptions. The first one
* will be used to create the Keycloak instance. The second one are options to initialize the
* keycloak instance.
*
* @param options
* Config: may be a string representing the keycloak URI or an object with the
* following content:
* - url: Keycloak json URL
* - realm: realm name
* - clientId: client id
*
* initOptions:
* - onLoad: Specifies an action to do on load. Supported values are 'login-required' or
* 'check-sso'.
* - token: Set an initial value for the token.
* - refreshToken: Set an initial value for the refresh token.
* - idToken: Set an initial value for the id token (only together with token or refreshToken).
* - timeSkew: Set an initial value for skew between local time and Keycloak server in seconds
* (only together with token or refreshToken).
* - checkLoginIframe: Set to enable/disable monitoring login state (default is true).
* - checkLoginIframeInterval: Set the interval to check login state (default is 5 seconds).
* - responseMode: Set the OpenID Connect response mode send to Keycloak server at login
* request. Valid values are query or fragment . Default value is fragment, which means
* that after successful authentication will Keycloak redirect to javascript application
* with OpenID Connect parameters added in URL fragment. This is generally safer and
* recommended over query.
* - flow: Set the OpenID Connect flow. Valid values are standard, implicit or hybrid.
*
* enableBearerInterceptor:
* Flag to indicate if the bearer will added to the authorization header.
*
* loadUserProfileInStartUp:
* Indicates that the user profile should be loaded at the keycloak initialization,
* just after the login.
*
* bearerExcludedUrls:
* String Array to exclude the urls that should not have the Authorization Header automatically
* added.
*
* authorizationHeaderName:
* This value will be used as the Authorization Http Header name.
*
* bearerPrefix:
* This value will be included in the Authorization Http Header param.
*
* @returns
* A Promise with a boolean indicating if the initialization was successful.
*/
/**
* Keycloak initialization. It should be called to initialize the adapter.
* Options is a object with 2 main parameters: config and initOptions. The first one
* will be used to create the Keycloak instance. The second one are options to initialize the
* keycloak instance.
*
* @param {?=} options
* Config: may be a string representing the keycloak URI or an object with the
* following content:
* - url: Keycloak json URL
* - realm: realm name
* - clientId: client id
*
* initOptions:
* - onLoad: Specifies an action to do on load. Supported values are 'login-required' or
* 'check-sso'.
* - token: Set an initial value for the token.
* - refreshToken: Set an initial value for the refresh token.
* - idToken: Set an initial value for the id token (only together with token or refreshToken).
* - timeSkew: Set an initial value for skew between local time and Keycloak server in seconds
* (only together with token or refreshToken).
* - checkLoginIframe: Set to enable/disable monitoring login state (default is true).
* - checkLoginIframeInterval: Set the interval to check login state (default is 5 seconds).
* - responseMode: Set the OpenID Connect response mode send to Keycloak server at login
* request. Valid values are query or fragment . Default value is fragment, which means
* that after successful authentication will Keycloak redirect to javascript application
* with OpenID Connect parameters added in URL fragment. This is generally safer and
* recommended over query.
* - flow: Set the OpenID Connect flow. Valid values are standard, implicit or hybrid.
*
* enableBearerInterceptor:
* Flag to indicate if the bearer will added to the authorization header.
*
* loadUserProfileInStartUp:
* Indicates that the user profile should be loaded at the keycloak initialization,
* just after the login.
*
* bearerExcludedUrls:
* String Array to exclude the urls that should not have the Authorization Header automatically
* added.
*
* authorizationHeaderName:
* This value will be used as the Authorization Http Header name.
*
* bearerPrefix:
* This value will be included in the Authorization Http Header param.
*
* @return {?}
* A Promise with a boolean indicating if the initialization was successful.
*/
KeycloakService.prototype.init = /**
* Keycloak initialization. It should be called to initialize the adapter.
* Options is a object with 2 main parameters: config and initOptions. The first one
* will be used to create the Keycloak instance. The second one are options to initialize the
* keycloak instance.
*
* @param {?=} options
* Config: may be a string representing the keycloak URI or an object with the
* following content:
* - url: Keycloak json URL
* - realm: realm name
* - clientId: client id
*
* initOptions:
* - onLoad: Specifies an action to do on load. Supported values are 'login-required' or
* 'check-sso'.
* - token: Set an initial value for the token.
* - refreshToken: Set an initial value for the refresh token.
* - idToken: Set an initial value for the id token (only together with token or refreshToken).
* - timeSkew: Set an initial value for skew between local time and Keycloak server in seconds
* (only together with token or refreshToken).
* - checkLoginIframe: Set to enable/disable monitoring login state (default is true).
* - checkLoginIframeInterval: Set the interval to check login state (default is 5 seconds).
* - responseMode: Set the OpenID Connect response mode send to Keycloak server at login
* request. Valid values are query or fragment . Default value is fragment, which means
* that after successful authentication will Keycloak redirect to javascript application
* with OpenID Connect parameters added in URL fragment. This is generally safer and
* recommended over query.
* - flow: Set the OpenID Connect flow. Valid values are standard, implicit or hybrid.
*
* enableBearerInterceptor:
* Flag to indicate if the bearer will added to the authorization header.
*
* loadUserProfileInStartUp:
* Indicates that the user profile should be loaded at the keycloak initialization,
* just after the login.
*
* bearerExcludedUrls:
* String Array to exclude the urls that should not have the Authorization Header automatically
* added.
*
* authorizationHeaderName:
* This value will be used as the Authorization Http Header name.
*
* bearerPrefix:
* This value will be included in the Authorization Http Header param.
*
* @return {?}
* A Promise with a boolean indicating if the initialization was successful.
*/
function (options) {
var _this = this;
if (options === void 0) {
options = {};
}
return new Promise(function (resolve, reject) {
_this._enableBearerInterceptor = _this.ifUndefinedIsTrue(options.enableBearerInterceptor);
_this._loadUserProfileAtStartUp = _this.ifUndefinedIsTrue(options.loadUserProfileAtStartUp);
_this._bearerExcludedUrls = options.bearerExcludedUrls || [];
_this._authorizationHeaderName = options.authorizationHeaderName || 'Authorization';
_this._bearerPrefix = _this.sanitizeBearerPrefix(options.bearerPrefix);
_this._silentRefresh = options.initOptions ? options.initOptions.flow === 'implicit' : false;
_this._instance = Keycloak(options.config);
_this.bindsKeycloakEvents();
_this._instance
.init(/** @type {?} */ ((options.initOptions)))
.success(function (authenticated) {
return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(authenticated && this._loadUserProfileAtStartUp))
return [3 /*break*/, 2];
return [4 /*yield*/, this.loadUserProfile()];
case 1:
_a.sent();
_a.label = 2;
case 2:
resolve(authenticated);
return [2 /*return*/];
}
});
});
})
.error(function (error) {
reject('An error happened during Keycloak initialization.');
});
});
};
/**
* Redirects to login form on (options is an optional object with redirectUri and/or
* prompt fields).
*
* @param options
* Object, where:
* - redirectUri: Specifies the uri to redirect to after login.
* - prompt:By default the login screen is displayed if the user is not logged-in to Keycloak.
* To only authenticate to the application if the user is already logged-in and not display the
* login page if the user is not logged-in, set this option to none. To always require
* re-authentication and ignore SSO, set this option to login .
* - maxAge: Used just if user is already authenticated. Specifies maximum time since the
* authentication of user happened. If user is already authenticated for longer time than
* maxAge, the SSO is ignored and he will need to re-authenticate again.
* - loginHint: Used to pre-fill the username/email field on the login form.
* - action: If value is 'register' then user is redirected to registration page, otherwise to
* login page.
* - locale: Specifies the desired locale for the UI.
* @returns
* A void Promise if the login is successful and after the user profile loading.
*/
/**
* Redirects to login form on (options is an optional object with redirectUri and/or
* prompt fields).
*
* @param {?=} options
* Object, where:
* - redirectUri: Specifies the uri to redirect to after login.
* - prompt:By default the login screen is displayed if the user is not logged-in to Keycloak.
* To only authenticate to the application if the user is already logged-in and not display the
* login page if the user is not logged-in, set this option to none. To always require
* re-authentication and ignore SSO, set this option to login .
* - maxAge: Used just if user is already authenticated. Specifies maximum time since the
* authentication of user happened. If user is already authenticated for longer time than
* maxAge, the SSO is ignored and he will need to re-authenticate again.
* - loginHint: Used to pre-fill the username/email field on the login form.
* - action: If value is 'register' then user is redirected to registration page, otherwise to
* login page.
* - locale: Specifies the desired locale for the UI.
* @return {?}
* A void Promise if the login is successful and after the user profile loading.
*/
KeycloakService.prototype.login = /**
* Redirects to login form on (options is an optional object with redirectUri and/or
* prompt fields).
*
* @param {?=} options
* Object, where:
* - redirectUri: Specifies the uri to redirect to after login.
* - prompt:By default the login screen is displayed if the user is not logged-in to Keycloak.
* To only authenticate to the application if the user is already logged-in and not display the
* login page if the user is not logged-in, set this option to none. To always require
* re-authentication and ignore SSO, set this option to login .
* - maxAge: Used just if user is already authenticated. Specifies maximum time since the
* authentication of user happened. If user is already authenticated for longer time than
* maxAge, the SSO is ignored and he will need to re-authenticate again.
* - loginHint: Used to pre-fill the username/email field on the login form.
* - action: If value is 'register' then user is redirected to registration page, otherwise to
* login page.
* - locale: Specifies the desired locale for the UI.
* @return {?}
* A void Promise if the login is successful and after the user profile loading.
*/
function (options) {
var _this = this;
if (options === void 0) {
options = {};
}
return new Promise(function (resolve, reject) {
_this._instance
.login(options)
.success(function () {
return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this._loadUserProfileAtStartUp)
return [3 /*break*/, 2];
return [4 /*yield*/, this.loadUserProfile()];
case 1:
_a.sent();
_a.label = 2;
case 2:
resolve();
return [2 /*return*/];
}
});
});
})
.error(function (error) {
reject('An error happened during the login.');
});
});
};
/**
* Redirects to logout.
*
* @param redirectUri
* Specifies the uri to redirect to after logout.
* @returns
* A void Promise if the logout was successful, cleaning also the userProfile.
*/
/**
* Redirects to logout.
*
* @param {?=} redirectUri
* Specifies the uri to redirect to after logout.
* @return {?}
* A void Promise if the logout was successful, cleaning also the userProfile.
*/
KeycloakService.prototype.logout = /**
* Redirects to logout.
*
* @param {?=} redirectUri
* Specifies the uri to redirect to after logout.
* @return {?}
* A void Promise if the logout was successful, cleaning also the userProfile.
*/
function (redirectUri) {
var _this = this;
return new Promise(function (resolve, reject) {
/** @type {?} */
var options = {
redirectUri: redirectUri
};
_this._instance
.logout(options)
.success(function () {
_this._userProfile = /** @type {?} */ ((undefined));
resolve();
})
.error(function (error) {
reject('An error happened during logout.');
});
});
};
/**
* Redirects to registration form. Shortcut for login with option
* action = 'register'. Options are same as for the login method but 'action' is set to
* 'register'.
*
* @param options
* login options
* @returns
* A void Promise if the register flow was successful.
*/
/**
* Redirects to registration form. Shortcut for login with option
* action = 'register'. Options are same as for the login method but 'action' is set to
* 'register'.
*
* @param {?=} options
* login options
* @return {?}
* A void Promise if the register flow was successful.
*/
KeycloakService.prototype.register = /**
* Redirects to registration form. Shortcut for login with option
* action = 'register'. Options are same as for the login method but 'action' is set to
* 'register'.
*
* @param {?=} options
* login options
* @return {?}
* A void Promise if the register flow was successful.
*/
function (options) {
var _this = this;
if (options === void 0) {
options = { action: 'register' };
}
return new Promise(function (resolve, reject) {
_this._instance
.register(options)
.success(function () {
resolve();
})
.error(function () {
reject('An error happened during the register execution');
});
});
};
/**
* Check if the user has access to the specified role. It will look for roles in
* realm and clientId, but will not check if the user is logged in for better performance.
*
* @param role
* role name
* @returns
* A boolean meaning if the user has the specified Role.
*/
/**
* Check if the user has access to the specified role. It will look for roles in
* realm and clientId, but will not check if the user is logged in for better performance.
*
* @param {?} role
* role name
* @return {?}
* A boolean meaning if the user has the specified Role.
*/
KeycloakService.prototype.isUserInRole = /**
* Check if the user has access to the specified role. It will look for roles in
* realm and clientId, but will not check if the user is logged in for better performance.
*
* @param {?} role
* role name
* @return {?}
* A boolean meaning if the user has the specified Role.
*/
function (role) {
/** @type {?} */
var hasRole;
hasRole = this._instance.hasResourceRole(role);
if (!hasRole) {
hasRole = this._instance.hasRealmRole(role);
}
return hasRole;
};
/**
* Return the roles of the logged user. The allRoles parameter, with default value
* true, will return the clientId and realm roles associated with the logged user. If set to false
* it will only return the user roles associated with the clientId.
*
* @param allRoles
* Flag to set if all roles should be returned.(Optional: default value is true)
* @returns
* Array of Roles associated with the logged user.
*/
/**
* Return the roles of the logged user. The allRoles parameter, with default value
* true, will return the clientId and realm roles associated with the logged user. If set to false
* it will only return the user roles associated with the clientId.
*
* @param {?=} allRoles
* Flag to set if all roles should be returned.(Optional: default value is true)
* @return {?}
* Array of Roles associated with the logged user.
*/
KeycloakService.prototype.getUserRoles = /**
* Return the roles of the logged user. The allRoles parameter, with default value
* true, will return the clientId and realm roles associated with the logged user. If set to false
* it will only return the user roles associated with the clientId.
*
* @param {?=} allRoles
* Flag to set if all roles should be returned.(Optional: default value is true)
* @return {?}
* Array of Roles associated with the logged user.
*/
function (allRoles) {
if (allRoles === void 0) {
allRoles = true;
}
/** @type {?} */
var roles = [];
if (this._instance.resourceAccess) {
for (var key in this._instance.resourceAccess) {
if (this._instance.resourceAccess.hasOwnProperty(key)) {
/** @type {?} */
var resourceAccess = this._instance.resourceAccess[key];
/** @type {?} */
var clientRoles = resourceAccess['roles'] || [];
roles = roles.concat(clientRoles);
}
}
}
if (allRoles && this._instance.realmAccess) {
/** @type {?} */
var realmRoles = this._instance.realmAccess['roles'] || [];
roles.push.apply(roles, __spread(realmRoles));
}
return roles;
};
/**
* Check if user is logged in.
*
* @returns
* A boolean that indicates if the user is logged in.
*/
/**
* Check if user is logged in.
*
* @return {?}
* A boolean that indicates if the user is logged in.
*/
KeycloakService.prototype.isLoggedIn = /**
* Check if user is logged in.
*
* @return {?}
* A boolean that indicates if the user is logged in.
*/
function () {
var _this = this;
return new Promise(function (resolve, reject) {
return __awaiter(_this, void 0, void 0, function () {
var error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.updateToken(20)];
case 1:
_a.sent();
resolve(true);
return [3 /*break*/, 3];
case 2:
error_1 = _a.sent();
resolve(false);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
});
});
};
/**
* Returns true if the token has less than minValidity seconds left before
* it expires.
*
* @param minValidity
* Seconds left. (minValidity) is optional. Default value is 0.
* @returns
* Boolean indicating if the token is expired.
*/
/**
* Returns true if the token has less than minValidity seconds left before
* it expires.
*
* @param {?=} minValidity
* Seconds left. (minValidity) is optional. Default value is 0.
* @return {?}
* Boolean indicating if the token is expired.
*/
KeycloakService.prototype.isTokenExpired = /**
* Returns true if the token has less than minValidity seconds left before
* it expires.
*
* @param {?=} minValidity
* Seconds left. (minValidity) is optional. Default value is 0.
* @return {?}
* Boolean indicating if the token is expired.
*/
function (minValidity) {
if (minValidity === void 0) {
minValidity = 0;
}
return this._instance.isTokenExpired(minValidity);
};
/**
* If the token expires within minValidity seconds the token is refreshed. If the
* session status iframe is enabled, the session status is also checked.
* Returns a promise telling if the token was refreshed or not. If the session is not active
* anymore, the promise is rejected.
*
* @param minValidity
* Seconds left. (minValidity is optional, if not specified 5 is used)
* @returns
* Promise with a boolean indicating if the token was succesfully updated.
*/
/**
* If the token expires within minValidity seconds the token is refreshed. If the
* session status iframe is enabled, the session status is also checked.
* Returns a promise telling if the token was refreshed or not. If the session is not active
* anymore, the promise is rejected.
*
* @param {?=} minValidity
* Seconds left. (minValidity is optional, if not specified 5 is used)
* @return {?}
* Promise with a boolean indicating if the token was succesfully updated.
*/
KeycloakService.prototype.updateToken = /**
* If the token expires within minValidity seconds the token is refreshed. If the
* session status iframe is enabled, the session status is also checked.
* Returns a promise telling if the token was refreshed or not. If the session is not active
* anymore, the promise is rejected.
*
* @param {?=} minValidity
* Seconds left. (minValidity is optional, if not specified 5 is used)
* @return {?}
* Promise with a boolean indicating if the token was succesfully updated.
*/
function (minValidity) {
var _this = this;
if (minValidity === void 0) {
minValidity = 5;
}
return new Promise(function (resolve, reject) {
return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
// TODO: this is a workaround until the silent refresh (issue #43)
// is not implemented, avoiding the redirect loop.
if (this._silentRefresh) {
if (this.isTokenExpired()) {
reject('Failed to refresh the token, or the session is expired');
}
else {
resolve(true);
}
return [2 /*return*/];
}
if (!this._instance) {
reject();
return [2 /*return*/];
}
this._instance
.updateToken(minValidity)
.success(function (refreshed) {
resolve(refreshed);
})
.error(function (error) {
reject('Failed to refresh the token, or the session is expired');
});
return [2 /*return*/];
});
});
});
};
/**
* Loads the users profile.
* Returns promise to set functions to be invoked if the profile was loaded successfully, or if
* the profile could not be loaded.
*
* @param forceReload
* If true will force the loadUserProfile even if its already loaded.
* @returns
* A promise with the KeycloakProfile data loaded.
*/
/**
* Loads the users profile.
* Returns promise to set functions to be invoked if the profile was loaded successfully, or if
* the profile could not be loaded.
*
* @param {?=} forceReload
* If true will force the loadUserProfile even if its already loaded.
* @return {?}
* A promise with the KeycloakProfile data loaded.
*/
KeycloakService.prototype.loadUserProfile = /**
* Loads the users profile.
* Returns promise to set functions to be invoked if the profile was loaded successfully, or if
* the profile could not be loaded.
*
* @param {?=} forceReload
* If true will force the loadUserProfile even if its already loaded.
* @return {?}
* A promise with the KeycloakProfile data loaded.
*/
function (forceReload) {
var _this = this;
if (forceReload === void 0) {
forceReload = false;
}
return new Promise(function (resolve, reject) {
return __awaiter(_this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this._userProfile && !forceReload) {
resolve(this._userProfile);
return [2 /*return*/];
}
return [4 /*yield*/, this.isLoggedIn()];
case 1:
if (!(_a.sent())) {
reject('The user profile was not loaded as the user is not logged in.');
return [2 /*return*/];
}
this._instance
.loadUserProfile()
.success(function (result) {
_this._userProfile = /** @type {?} */ (result);
resolve(_this._userProfile);
})
.error(function (err) {
reject('The user profile could not be loaded.');
});
return [2 /*return*/];
}
});
});
});
};
/**
* Returns the authenticated token, calling updateToken to get a refreshed one if
* necessary. If the session is expired this method calls the login method for a new login.
*
* @returns
* Promise with the generated token.
*/
/**
* Returns the authenticated token, calling updateToken to get a refreshed one if
* necessary. If the session is expired this method calls the login method for a new login.
*
* @return {?}
* Promise with the generated token.
*/
KeycloakService.prototype.getToken = /**
* Returns the authenticated token, calling updateToken to get a refreshed on