Get Authorization token to call API

匆匆过客 提交于 2020-08-11 11:09:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!