Reputation: 1665
I stitched together a lot of tutorials and documentation in order to get an access token with MSALin my JavaScript code. Here are the results of my research.
Upvotes: 7
Views: 44526
Reputation: 11
Only works if you actually do a redirect: next time, once logged in, you won't get your console message.
Based on this guide (https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-spa-acquire-token?tabs=javascript2) I came up with the following
this.msalsrv.handleRedirectObservable().subscribe( (redirectResponse) => {
if(redirectResponse != null) {
// Acquire token silent success
let accessToken = redirectResponse.accessToken;
// Call your API with token
console.log("We got the token! hahaha: " + accessToken);
}
})
Made another try and figured out how to get the token. Make sure to use this code once the login processed has alredy been perfomed (for example if you're a page under MsalGuard).
const accessTokenRequest = {
scopes: ["user.read"],
account: this.msalsrv.instance.getAllAccounts()[0],
};
this.msalsrv.acquireTokenSilent(accessTokenRequest).subscribe( (accessTokenReponse) => {
if(accessTokenReponse != null) {
// Acquire token silent success
let accessToken = accessTokenReponse.accessToken;
// Call your API with token
console.log("We got the token! hahaha: " + accessToken);
}
})
Notice this code just works.. you have to ensure what happens if your session has expired.
Upvotes: 0
Reputation: 1665
npm install @azure/msal
import the necessary class from @azure/msal
import {
UserAgentApplication,
AuthenticationParameters,
Configuration,
} from "@azure/msal";
Make the msal object
const config: Configuration = {
auth: {
clientId: <client id - your app's client id>,
authority: `https://login.microsoftonline.com/<tenantid>`,
redirectUri: <the redirect Uri>,
},
};
const params: AuthenticationParameters = {
authority: `https://login.microsoftonline.com/${Tenantid}`,
scopes: [`${AppIDUri}/user_impersonation`], <-- the API that you're trying to call
};
const myMSAL = new UserAgentApplication(config);
Get access token
try {
const login = await myMSAL.acquireTokenSilent(params);
return login.accessToken;
} catch (error) {
await myMSAL.loginPopup(params);
const login = await myMSAL.acquireTokenSilent(params);
return login.accessToken;
}
References:
https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-acquire-cache-tokens
Azure/Msal authentication inside PowerApp Component Framework returns AADSTS50177 error
Upvotes: 7