问题
I'm trying to call the API that I created by following these directions, I got to the point where I can call the API from Developer Portal using the JWT token.
Now I'm confused, how will the angular client app get this JWT token in order to call the API?
Currently, users of the angular app are in the Active Directory (same AD that was used in directions to set up the API). The sign-in process is done through MSAL library. When I try to get the token by calling acquireTokenSilent and try to call the API using this token, I get 401 error.
How do I get the correct JTW token from the angular app?
回答1:
Make sure you grant permissions for your client app with the permissions you exposed in the api app, follow this doc.
Then in the consentScopes , use the api scope of your api, you can find the Application ID URL
in the Expose an API
page of your API App, e.g. something like api://xxxxxxxxxxxxxxx/api_usage
consentScopes: [
'<Application ID URL>/scope'
],
When you get the token, use ["<Application ID URL>/scope"]
for the scopes
.
const requestObj = {
scopes: ["<Application ID URL>/scope"]
};
this.authService.acquireTokenSilent(requestObj).then(function (tokenResponse) {
// Callback code here
console.log(tokenResponse.accessToken);
}).catch(function (error) {
console.log(error);
});
Fore more details, refer to Tutorial: Sign in users and call the Microsoft Graph API from an Angular single-page application. In this doc, it calls the MS Graph, to call your own api, change the scopes and it should work.
回答2:
You may not able to get the token using acquireTokenSilentAsync in the case where the session has already expired or within grace period. when it failed to get the token, call acquireTokenAsync will redirect the user to enter their password to sign-in.
authContext
.acquireTokenSilentAsync(x,y,z)
.then((authResponse: AuthenticationResult) => {
// process authResponse
})
.catch(() => {
authContext
.acquireTokenAsync(x,y,x,"")
.then((authResponse: AuthenticationResult) => {
// process authResponse
}).catch(() => {
//do things
}).finally(() => {
//do things
});
});
来源:https://stackoverflow.com/questions/63291339/get-authorization-token-to-call-api