UNPKG

@brionmario-experimental/asgardeo-auth-spa

Version:

Asgardeo Auth SPA SDK to be used in Single-Page Applications.

308 lines 16.6 kB
/** * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 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) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { AUTHORIZATION_CODE, AsgardeoAuthClient, AuthenticationUtils, ResponseMode, SESSION_STATE, STATE } from "@asgardeo/auth-js"; import { SILENT_SIGN_IN_STATE, Storage, TOKEN_REQUEST_CONFIG_KEY } from "../constants"; import { SPAHelper, SessionManagementHelper } from "../helpers"; import { HttpClient } from "../http-client"; import { LocalStore, MemoryStore, SessionStore } from "../stores"; import { SPAUtils } from "../utils"; import { SPACryptoUtils } from "../utils/crypto-utils"; const initiateStore = (store) => { switch (store) { case Storage.LocalStorage: return new LocalStore(); case Storage.SessionStorage: return new SessionStore(); case Storage.BrowserMemory: return new MemoryStore(); default: return new SessionStore(); } }; export const MainThreadClient = (instanceID, config, getAuthHelper) => __awaiter(void 0, void 0, void 0, function* () { var _a; const _store = initiateStore(config.storage); const _cryptoUtils = new SPACryptoUtils(); const _authenticationClient = new AsgardeoAuthClient(); yield _authenticationClient.initialize(config, _store, _cryptoUtils, instanceID); const _spaHelper = new SPAHelper(_authenticationClient); const _dataLayer = _authenticationClient.getDataLayer(); const _sessionManagementHelper = yield SessionManagementHelper(() => __awaiter(void 0, void 0, void 0, function* () { return _authenticationClient.getSignOutURL(); }), (_a = config.storage) !== null && _a !== void 0 ? _a : Storage.SessionStorage, (sessionState) => _dataLayer.setSessionDataParameter(SESSION_STATE, sessionState !== null && sessionState !== void 0 ? sessionState : "")); const _authenticationHelper = getAuthHelper(_authenticationClient, _spaHelper); let _getSignOutURLFromSessionStorage = false; const _httpClient = HttpClient.getInstance(); let _isHttpHandlerEnabled = true; let _httpErrorCallback; let _httpFinishCallback; const attachToken = (request) => __awaiter(void 0, void 0, void 0, function* () { yield _authenticationHelper.attachTokenToRequestConfig(request); }); (_httpClient === null || _httpClient === void 0 ? void 0 : _httpClient.init) && (yield _httpClient.init(true, attachToken)); const setHttpRequestStartCallback = (callback) => { (_httpClient === null || _httpClient === void 0 ? void 0 : _httpClient.setHttpRequestStartCallback) && _httpClient.setHttpRequestStartCallback(callback); }; const setHttpRequestSuccessCallback = (callback) => { (_httpClient === null || _httpClient === void 0 ? void 0 : _httpClient.setHttpRequestSuccessCallback) && _httpClient.setHttpRequestSuccessCallback(callback); }; const setHttpRequestFinishCallback = (callback) => { (_httpClient === null || _httpClient === void 0 ? void 0 : _httpClient.setHttpRequestFinishCallback) && _httpClient.setHttpRequestFinishCallback(callback); }; const setHttpRequestErrorCallback = (callback) => { _httpErrorCallback = callback; }; const httpRequest = (requestConfig) => __awaiter(void 0, void 0, void 0, function* () { return yield _authenticationHelper.httpRequest(_httpClient, requestConfig, _isHttpHandlerEnabled, _httpErrorCallback, _httpFinishCallback); }); const httpRequestAll = (requestConfigs) => __awaiter(void 0, void 0, void 0, function* () { return yield _authenticationHelper.httpRequestAll(requestConfigs, _httpClient, _isHttpHandlerEnabled, _httpErrorCallback, _httpFinishCallback); }); const getHttpClient = () => { return _httpClient; }; const enableHttpHandler = () => { _authenticationHelper.enableHttpHandler(_httpClient); _isHttpHandlerEnabled = true; return true; }; const disableHttpHandler = () => { _authenticationHelper.disableHttpHandler(_httpClient); _isHttpHandlerEnabled = false; return true; }; const checkSession = () => __awaiter(void 0, void 0, void 0, function* () { const oidcEndpoints = yield _authenticationClient.getOIDCServiceEndpoints(); const config = yield _dataLayer.getConfigData(); _authenticationHelper.initializeSessionManger(config, oidcEndpoints, () => __awaiter(void 0, void 0, void 0, function* () { return (yield _authenticationClient.getBasicUserInfo()).sessionState; }), (params) => __awaiter(void 0, void 0, void 0, function* () { return _authenticationClient.getAuthorizationURL(params); }), _sessionManagementHelper); }); const shouldStopAuthn = () => __awaiter(void 0, void 0, void 0, function* () { return yield _sessionManagementHelper.receivePromptNoneResponse((sessionState) => __awaiter(void 0, void 0, void 0, function* () { yield _dataLayer.setSessionDataParameter(SESSION_STATE, sessionState !== null && sessionState !== void 0 ? sessionState : ""); return; })); }); const setSessionStatus = (sessionStatus) => __awaiter(void 0, void 0, void 0, function* () { yield _dataLayer.setSessionStatus(sessionStatus); }); const signIn = (signInConfig, authorizationCode, sessionState, state, tokenRequestConfig) => __awaiter(void 0, void 0, void 0, function* () { var _b, _c, _d; const basicUserInfo = yield _authenticationHelper.handleSignIn(shouldStopAuthn, checkSession, undefined); if (basicUserInfo) { return basicUserInfo; } else { let resolvedAuthorizationCode; let resolvedSessionState; let resolvedState; let resolvedTokenRequestConfig = { params: {} }; if ((config === null || config === void 0 ? void 0 : config.responseMode) === ResponseMode.formPost && authorizationCode) { resolvedAuthorizationCode = authorizationCode; resolvedSessionState = sessionState !== null && sessionState !== void 0 ? sessionState : ""; resolvedState = state !== null && state !== void 0 ? state : ""; } else { resolvedAuthorizationCode = (_b = new URL(window.location.href).searchParams.get(AUTHORIZATION_CODE)) !== null && _b !== void 0 ? _b : ""; resolvedSessionState = (_c = new URL(window.location.href).searchParams.get(SESSION_STATE)) !== null && _c !== void 0 ? _c : ""; resolvedState = (_d = new URL(window.location.href).searchParams.get(STATE)) !== null && _d !== void 0 ? _d : ""; SPAUtils.removeAuthorizationCode(); } if (resolvedAuthorizationCode && resolvedState) { setSessionStatus("true"); const storedTokenRequestConfig = yield _dataLayer.getTemporaryDataParameter(TOKEN_REQUEST_CONFIG_KEY); if (storedTokenRequestConfig && typeof storedTokenRequestConfig === "string") { resolvedTokenRequestConfig = JSON.parse(storedTokenRequestConfig); } return requestAccessToken(resolvedAuthorizationCode, resolvedSessionState, resolvedState, resolvedTokenRequestConfig); } return _authenticationClient.getAuthorizationURL(signInConfig).then((url) => __awaiter(void 0, void 0, void 0, function* () { if (config.storage === Storage.BrowserMemory && config.enablePKCE) { const pkceKey = AuthenticationUtils.extractPKCEKeyFromStateParam(resolvedState); SPAUtils.setPKCE(pkceKey, (yield _authenticationClient.getPKCECode(resolvedState))); } if (tokenRequestConfig) { _dataLayer.setTemporaryDataParameter(TOKEN_REQUEST_CONFIG_KEY, JSON.stringify(tokenRequestConfig)); } location.href = url; yield SPAUtils.waitTillPageRedirect(); return Promise.resolve({ allowedScopes: "", displayName: "", email: "", sessionState: "", sub: "", tenantDomain: "", username: "" }); })); } }); const signOut = () => __awaiter(void 0, void 0, void 0, function* () { if ((yield _authenticationClient.isAuthenticated()) && !_getSignOutURLFromSessionStorage) { location.href = yield _authenticationClient.getSignOutURL(); } else { location.href = SPAUtils.getSignOutURL(config.clientID, instanceID); } _spaHelper.clearRefreshTokenTimeout(); yield _dataLayer.removeOIDCProviderMetaData(); yield _dataLayer.removeTemporaryData(); yield _dataLayer.removeSessionData(); yield _dataLayer.removeSessionStatus(); yield SPAUtils.waitTillPageRedirect(); return true; }); const enableRetrievingSignOutURLFromSession = (config) => { if (config.preventSignOutURLUpdate) { _getSignOutURLFromSessionStorage = true; } }; const requestCustomGrant = (config) => __awaiter(void 0, void 0, void 0, function* () { return yield _authenticationHelper.requestCustomGrant(config, enableRetrievingSignOutURLFromSession); }); const refreshAccessToken = () => __awaiter(void 0, void 0, void 0, function* () { try { return yield _authenticationHelper.refreshAccessToken(enableRetrievingSignOutURLFromSession); } catch (error) { return Promise.reject(error); } }); const revokeAccessToken = () => __awaiter(void 0, void 0, void 0, function* () { const timer = yield _spaHelper.getRefreshTimeoutTimer(); return _authenticationClient .revokeAccessToken() .then(() => { _sessionManagementHelper.reset(); _spaHelper.clearRefreshTokenTimeout(timer); return Promise.resolve(true); }) .catch((error) => Promise.reject(error)); }); const requestAccessToken = (resolvedAuthorizationCode, resolvedSessionState, resolvedState, tokenRequestConfig) => __awaiter(void 0, void 0, void 0, function* () { return yield _authenticationHelper.requestAccessToken(resolvedAuthorizationCode, resolvedSessionState, checkSession, undefined, resolvedState, tokenRequestConfig); }); const constructSilentSignInUrl = (additionalParams = {}) => __awaiter(void 0, void 0, void 0, function* () { const config = yield _dataLayer.getConfigData(); const urlString = yield _authenticationClient.getAuthorizationURL(Object.assign({ prompt: "none", state: SILENT_SIGN_IN_STATE }, additionalParams)); // Replace form_post with query const urlObject = new URL(urlString); urlObject.searchParams.set("response_mode", "query"); const url = urlObject.toString(); if (config.storage === Storage.BrowserMemory && config.enablePKCE) { const state = urlObject.searchParams.get(STATE); SPAUtils.setPKCE(AuthenticationUtils.extractPKCEKeyFromStateParam(state !== null && state !== void 0 ? state : ""), (yield _authenticationClient.getPKCECode(state !== null && state !== void 0 ? state : ""))); } return url; }); /** * This method checks if there is an active user session in the server by sending a prompt none request. * If the user is signed in, this method sends a token request. Returns false otherwise. * * @return {Promise<BasicUserInfo|boolean} Returns a Promise that resolves with the BasicUserInfo * if the user is signed in or with `false` if there is no active user session in the server. */ const trySignInSilently = (additionalParams, tokenRequestConfig) => __awaiter(void 0, void 0, void 0, function* () { return yield _authenticationHelper.trySignInSilently(constructSilentSignInUrl, requestAccessToken, _sessionManagementHelper, additionalParams, tokenRequestConfig); }); const getBasicUserInfo = () => __awaiter(void 0, void 0, void 0, function* () { return _authenticationHelper.getBasicUserInfo(); }); const getDecodedIDToken = () => __awaiter(void 0, void 0, void 0, function* () { return _authenticationHelper.getDecodedIDToken(); }); const getCryptoHelper = () => __awaiter(void 0, void 0, void 0, function* () { return _authenticationHelper.getCryptoHelper(); }); const getIDToken = () => __awaiter(void 0, void 0, void 0, function* () { return _authenticationHelper.getIDToken(); }); const getOIDCServiceEndpoints = () => __awaiter(void 0, void 0, void 0, function* () { return _authenticationHelper.getOIDCServiceEndpoints(); }); const getAccessToken = () => __awaiter(void 0, void 0, void 0, function* () { return _authenticationHelper.getAccessToken(); }); const getDataLayer = () => __awaiter(void 0, void 0, void 0, function* () { return _authenticationHelper.getDataLayer(); }); const getConfigData = () => __awaiter(void 0, void 0, void 0, function* () { return yield _dataLayer.getConfigData(); }); const isAuthenticated = () => __awaiter(void 0, void 0, void 0, function* () { return _authenticationHelper.isAuthenticated(); }); const isSessionActive = () => __awaiter(void 0, void 0, void 0, function* () { return (yield _dataLayer.getSessionStatus()) === "true"; }); const updateConfig = (newConfig) => __awaiter(void 0, void 0, void 0, function* () { const existingConfig = yield _dataLayer.getConfigData(); const isCheckSessionIframeDifferent = !(existingConfig && existingConfig.endpoints && existingConfig.endpoints.checkSessionIframe && newConfig && newConfig.endpoints && newConfig.endpoints.checkSessionIframe && existingConfig.endpoints.checkSessionIframe === newConfig.endpoints.checkSessionIframe); const config = Object.assign(Object.assign({}, existingConfig), newConfig); yield _authenticationClient.updateConfig(config); // Re-initiates check session if the check session endpoint is updated. if (config.enableOIDCSessionManagement && isCheckSessionIframeDifferent) { _sessionManagementHelper.reset(); checkSession(); } }); return { disableHttpHandler, enableHttpHandler, getAccessToken, getBasicUserInfo, getConfigData, getCryptoHelper, getDataLayer, getDecodedIDToken, getHttpClient, getIDToken, getOIDCServiceEndpoints, httpRequest, httpRequestAll, isAuthenticated, isSessionActive, refreshAccessToken, requestCustomGrant, revokeAccessToken, setHttpRequestErrorCallback, setHttpRequestFinishCallback, setHttpRequestStartCallback, setHttpRequestSuccessCallback, signIn, signOut, trySignInSilently, updateConfig }; }); //# sourceMappingURL=main-thread-client.js.map