This repository has been archived on 2025-08-13. You can view files and clone it, but cannot push or open issues or pull requests.
Files
KTUSA-PS/KTUSAPS/ClientApp/src/msal.js
2022-01-26 19:53:41 +02:00

170 lines
4.9 KiB
JavaScript

import * as msal from '@azure/msal-browser'
import axios from 'axios'
const ClientIdCookieName = 'ktusakacas'
const AuthorityCookieName = 'ktusakeksas'
const TenantCookieName = 'ktusalaimis'
const RequestedScopes = ['openid', 'email', 'profile']
const msalState = {
msal: null,
clientId: null, // 5931fda0-e9e0-4754-80c2-18bcb9d9561a
authority: null, // https://login.microsoftonline.com/3415f2f7-f5a8-4092-b52a-003aaf844853/v2.0
tenant: null, // 3415f2f7-f5a8-4092-b52a-003aaf844853,
stateChangeCallbacks: [],
isLoggedIn: false,
accessToken: null,
idToken: null,
email: null,
displayName: null,
debugFullTokenResponse: null,
msalRefreshTimer: null,
}
async function initializeMSAL() {
if (msalState.msal != null) {
throw new Error('MSAL was attempted to initialize second time')
}
await __loadAuthParameters()
const msalConfig = {
auth: {
clientId: msalState.clientId,
authority: `https://login.microsoftonline.com/${msalState.tenant}`,
redirectUri: window.location.protocol + '//' + window.location.host + '/',
},
}
msalState.msalRefreshTimer = setInterval(__refreshToken, 10 * 60 * 1000)
msalState.msal = new msal.PublicClientApplication(msalConfig)
msalState.msal.handleRedirectPromise().then(__handleResponse)
window.msalState = msalState
}
export function WatchMsalState(callback) {
msalState.stateChangeCallbacks.push(callback)
callback()
}
export function GetMsalState() {
return {
accessToken: msalState.accessToken,
idToken: msalState.idToken,
isLoggedIn: msalState.isLoggedIn,
debugFullTokenResponse: msalState.debugFullTokenResponse,
debugAccountInfo: msalState.debugAccountInfo,
email: msalState.email,
displayName: msalState.displayName,
}
}
export function LoginMsal() {
msalState.msal.loginRedirect({
scopes: RequestedScopes,
})
}
export function LogoutMsal() {
msalState.msal.logout()
}
async function __refreshToken() {
if (!msalState.isLoggedIn) return
msalState.debugFullTokenResponse = await msalState.msal
.acquireTokenSilent({ scopes: RequestedScopes })
.catch((error) => {
if (error instanceof msal.InteractionRequiredAuthError) {
// fallback to interaction when silent call fails
return msalState.msal.acquireTokenRedirect({
scopes: RequestedScopes,
})
}
})
__responseObjectToMsalState()
__stateChanged()
}
async function __handleResponse(response) {
if (response !== null) {
if (__isAccountAceptable(response.account)) {
msalState.msal.setActiveAccount(response)
msalState.debugFullTokenResponse = response
__responseObjectToMsalState()
}
} else {
msalState.msal
.getAllAccounts()
.filter(__isAccountAceptable)
.forEach((account) => {
msalState.msal.setActiveAccount(account)
})
const account = msalState.msal.getActiveAccount()
if (account != null) {
msalState.debugFullTokenResponse = await msalState.msal
.acquireTokenSilent({ scopes: RequestedScopes })
.catch((error) => {
if (error instanceof msal.InteractionRequiredAuthError) {
// fallback to interaction when silent call fails
return msalState.msal.acquireTokenRedirect({
scopes: RequestedScopes,
})
}
})
__responseObjectToMsalState()
}
}
__stateChanged()
}
function __responseObjectToMsalState() {
msalState.isLoggedIn = true
msalState.accessToken = msalState.debugFullTokenResponse.accessToken
msalState.idToken = msalState.debugFullTokenResponse.idToken
msalState.email = msalState.debugFullTokenResponse.idTokenClaims.email
msalState.displayName = msalState.debugFullTokenResponse.idTokenClaims.name
}
function __isAccountAceptable(account) {
if (account.tenantId != msalState.tenant) return false
return true
}
function __stateChanged() {
msalState.stateChangeCallbacks.forEach((cb) => cb())
}
async function __loadAuthParameters() {
await __loadAuthParametersLocalStorage()
}
async function __loadAuthParametersLocalStorage() {
const clientId = localStorage.getItem(ClientIdCookieName)
const authority = localStorage.getItem(AuthorityCookieName)
const tenant = localStorage.getItem(TenantCookieName)
if (clientId == null || authority == null || tenant == null) {
await __fetchAuthParameters()
localStorage.setItem(ClientIdCookieName, msalState.clientId)
localStorage.setItem(AuthorityCookieName, msalState.authority)
localStorage.setItem(TenantCookieName, msalState.tenant)
} else {
msalState.clientId = clientId
msalState.authority = authority
msalState.tenant = tenant
}
}
async function __fetchAuthParameters() {
var response = await axios.get('/api/AuthMetadata')
msalState.clientId = response.data.clientId
msalState.authority = response.data.authority
msalState.tenant = response.data.tenant
}
initializeMSAL()