UNPKG

keycloak-angular

Version:
1,217 lines (1,212 loc) 102 kB
import { __awaiter, __generator, __spread } from 'tslib'; import { Injectable, NgModule } from '@angular/core'; import { HttpHeaders, HTTP_INTERCEPTORS } from '@angular/common/http'; import * as Keycloak_ from 'keycloak-js'; import { Observable, Subject } from 'rxjs'; import { mergeMap } from 'rxjs/operators'; import { CommonModule } from '@angular/common'; /** * @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'; /** * @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 = /** @class */ (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 = /** @class */ (function () { function KeycloakService() { this._keycloakEvents$ = new 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 one if * necessary. If the session is expired this method calls the login method for a new login. * * @return {?} * Promise with the generated token. */ function () { var _this = this; return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { var error_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.updateToken(10)]; case 1: _a.sent(); resolve(this._instance.token); return [3 /*break*/, 3]; case 2: error_2 = _a.sent(); this.login(); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }); }; /** * Returns the logged username. * * @returns * The logged username. */ /** * Returns the logged username. * * @return {?} * The logged username. */ KeycloakService.prototype.getUsername = /** * Returns the logged username. * * @return {?} * The logged username. */ function () { if (!this._userProfile) { throw new Error('User not logged in or user profile was not loaded.'); } return /** @type {?} */ ((this._userProfile.username)); }; /** * Clear authentication state, including tokens. This can be useful if application * has detected the session was expired, for example if updating token fails. * Invoking this results in onAuthLogout callback listener being invoked. */ /** * Clear authentication state, including tokens. This can be useful if application * has detected the session was expired, for example if updating token fails. * Invoking this results in onAuthLogout callback listener being invoked. * @return {?} */ KeycloakService.prototype.clearToken = /** * Clear authentication state, including tokens. This can be useful if application * has detected the session was expired, for example if updating token fails. * Invoking this results in onAuthLogout callback listener being invoked. * @return {?} */ function () { this._instance.clearToken(); }; /** * Adds a valid token in header. The key & value format is: * Authorization Bearer <token>. * If the headers param is undefined it will create the Angular headers object. * * @param headers * Updated header with Authorization and Keycloak token. * @returns * An observable with with the HTTP Authorization header and the current token. */ /** * Adds a valid token in header. The key & value format is: * Authorization Bearer <token>. * If the headers param is undefined it will create the Angular headers object. * * @param {?=} headersArg * @return {?} * An observable with with the HTTP Authorization header and the current token. */ KeycloakService.prototype.addTokenToHeader = /** * Adds a valid token in header. The key & value format is: * Authorization Bearer <token>. * If the headers param is undefined it will create the Angular headers object. * * @param {?=} headersArg * @return {?} * An observable with with the HTTP Authorization header and the current token. */ function (headersArg) { var _this = this; return Observable.create(function (observer) { return __awaiter(_this, void 0, void 0, function () { var headers, token, error_3; return __generator(this, function (_a) { switch (_a.label) { case 0: headers = headersArg; if (!headers) { headers = new HttpHeaders(); } _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this.getToken()]; case 2: token = _a.sent(); headers = headers.set(this._authorizationHeaderName, this._bearerPrefix + token); observer.next(headers); observer.complete(); return [3 /*break*/, 4]; case 3: error_3 = _a.sent(); observer.error(error_3); return [3 /*break*/, 4]; case 4: return [2 /*return*/]; } }); }); }); }; /** * Returns the original Keycloak instance, if you need any customization that * this Angular service does not support yet. Use with caution. * * @returns * The KeycloakInstance from keycloak-js. */ /** * Returns the original Keycloak instance, if you need any customization that * this Angular service does not support yet. Use with caution. * * @return {?} * The KeycloakInstance from keycloak-js. */ KeycloakService.prototype.getKeycloakInstance = /** * Returns the original Keycloak instance, if you need any customization that * this Angular service does not support yet. Use with caution. * * @return {?} * The KeycloakInstance from keycloak-js. */ function () { return this._instance; }; Object.defineProperty(KeycloakService.prototype, "bearerExcludedUrls", { /** * Returns the excluded URLs that should not be considered by * the http interceptor which automatically adds the authorization header in the Http Request. * * @returns * The excluded urls that must not be intercepted by the KeycloakBearerInterceptor. */ get: /** * Returns the excluded URLs that should not be considered by * the http interceptor which automatically adds the authorization header in the Http Request. * * @return {?} * The excluded urls that must not be intercepted by the KeycloakBearerInterceptor. */ function () { return this._bearerExcludedUrls; }, enumerable: true, configurable: true }); Object.defineProperty(KeycloakService.prototype, "enableBearerInterceptor", { /** * Flag to indicate if the bearer will be added to the authorization header. * * @returns * Returns if the bearer interceptor was set to be disabled. */ get: /** * Flag to indicate if the bearer will be added to the authorization header. * * @return {?} * Returns if the bearer interceptor was set to be disabled. */ function () { return this._enableBearerInterceptor; }, enumerable: true, configurable: true }); Object.defineProperty(KeycloakService.prototype, "keycloakEvents$", { /** * Keycloak subject to monitor the events triggered by keycloak-js. * The following events as available (as described at keycloak docs - * https://www.keycloak.org/docs/latest/securing_apps/index.html#callback-events): * - OnAuthError * - OnAuthLogout * - OnAuthRefreshError * - OnAuthRefreshSuccess * - OnAuthSuccess * - OnReady * - OnTokenExpire * In each occurrence of any of these, this subject will return the event type, * described at {@link KeycloakEventType} enum and the function args from the keycloak-js * if provided any. * * @returns * A subject with the {@link KeycloakEvent} which describes the event type and attaches the * function args. */ get: /** * Keycloak subject to monitor the events triggered by keycloak-js. * The following events as available (as described at keycloak docs - * https://www.keycloak.org/docs/latest/securing_apps/index.html#callback-events): * - OnAuthError * - OnAuthLogout * - OnAuthRefreshError * - OnAuthRefreshSuccess * - OnAuthSuccess * - OnReady * - OnTokenExpire * In each occurrence of any of these, this subject will return the event type, * described at {\@link KeycloakEventType} enum and the function args from the keycloak-js * if provided any. * * @return {?} * A subject with the {\@link KeycloakEvent} which describes the event type and attaches the * function args. */ function () { return this._keycloakEvents$; }, enumerable: true, configurable: true }); KeycloakService.decorators = [ { type: Injectable }, ]; /** @nocollapse */ KeycloakService.ctorParameters = function () { return []; }; return KeycloakService; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * This interceptor includes the bearer by default in all HttpClient requests. * * If you need to exclude some URLs from adding the bearer, please, take a look * at the {\@link KeycloakOptions} bearerExcludedUrls property. */ var KeycloakBearerInterceptor = /** @class */ (function () { /** * KeycloakBearerInterceptor constructor. * * @param keycloak - Injected KeycloakService instance. */ function KeycloakBearerInterceptor(keycloak) { this.keycloak = keycloak; } /** * @return {?} */ KeycloakBearerInterceptor.prototype.loadExcludedUrlsRegex = /** * @return {?} */ function () { /** @type {?} */ var excludedUrls = this.keycloak.bearerExcludedUrls; this.excludedUrlsRegex = excludedUrls.map(function (urlPattern) { return new RegExp(urlPattern, 'i'); }) || []; }; /** * Intercept implementation that checks if the request url matches the excludedUrls. * If not, adds the Authorization header to the request. * * @param {?} req * @param {?} next * @return {?} */ KeycloakBearerInterceptor.prototype.intercept = /** * Intercept implementation that checks if the request url matches the excludedUrls. * If not, adds the Authorization header to the request. * * @param {?} req * @param {?} next * @return {?} */ function (req, next) { // If keycloak service is not initialized yet, or the interceptor should not be execute if (!this.keycloak || !this.keycloak.enableBearerInterceptor) { return next.handle(req); } if (!this.excludedUrlsRegex) { this.loadExcludedUrlsRegex(); } /** @type {?} */ var urlRequest = req.url; /** @type {?} */ var shallPass = !!this.excludedUrlsRegex.find(function (regex) { return regex.test(urlRequest); }); if (shallPass) { return next.handle(req); } return this.keycloak.addTokenToHeader(req.headers).pipe(mergeMap(function (headersWithBearer) {