Authentication
Web v4
mapsindoors.MapsIndoors.onAuthRequired = async ({ authClients = [], authIssuer = '' }) => {
...
})import { AuthorizationRequest, AuthorizationNotifier, BaseTokenRequestHandler, RedirectRequestHandler, AuthorizationServiceConfiguration, FetchRequestor, TokenRequest, GRANT_TYPE_AUTHORIZATION_CODE } from "@openid/appauth";
const requestor = new FetchRequestor();
const authorizationNotifier = new AuthorizationNotifier();
const authorizationHandler = new RedirectRequestHandler();
mapsindoors.MapsIndoors.onAuthRequired = async ({ authClients = [], authIssuer = '' }) => {
//Fetch the service configuration.
const config = await AuthorizationServiceConfiguration.fetchFromIssuer(authIssuer, requestor);
//Check if the URL contains code and state in the hash. They will only be present after the authorization is done.
if (window.location.hash.includes('code') && window.location.hash.includes('state')) {
//Next we need to exchange the code to an access token.
authorizationHandler.setAuthorizationNotifier(authorizationNotifier);
authorizationNotifier.setAuthorizationListener(async (request, response, error) => {
if (response) {
const tokenHandler = new BaseTokenRequestHandler(requestor);
//Build the token request.
const tokenRequest = new TokenRequest({
client_id: request.clientId,
redirect_uri: `${window.location.origin}${window.location.pathname}`,
grant_type: GRANT_TYPE_AUTHORIZATION_CODE,
code: response.code,
state: '',
extras: { code_verifier: request?.internal?.code_verifier }
});
//Send the token request.
tokenHandler.performTokenRequest(config, tokenRequest).then(response => {
//Assign the access to ken to MapsIndoors.
mapsindoors.MapsIndoors.setAuthToken(response.accessToken);
});
}
});
await authorizationHandler.completeAuthorizationRequestIfPossible();
} else {
const authClient = authClients[0];
const preferredIDP = authClient.preferredIDPs && authClient.preferredIDPs.length > 0 ? authClient.preferredIDPs[0] : '';
//Build to authorization request.
const request = new AuthorizationRequest({
client_id: authClient.clientId,
redirect_uri: `${window.location.origin}${window.location.pathname}`,
scope: 'openid profile account client-apis',
response_type: AuthorizationRequest.RESPONSE_TYPE_CODE,
extras: { 'acr_values': `idp:${preferredIDP}`, 'response_mode': 'fragment' }
});
//Send the authorization request.
authorizationHandler.performAuthorizationRequest(config, request);
}
//Clean up the url when the authentication is done.
history.replaceState(null, '', `${window.location.origin}${window.location.pathname}${window.location.search}`);
})Last updated
Was this helpful?