获取授权令牌以调用API

时间:2020-08-06 20:32:57

标签: angular azure azure-api-management msal

我正在尝试调用following these directions创建的API,现在我可以使用JWT令牌从Developer Portal调用API。

现在我很困惑,Angular客户端应用程序将如何获取此JWT令牌以调用API?

当前,Angular应用程序的用户位于Active Directory(用于设置API的指导中使用的同一AD)中。登录过程是通过MSAL library完成的。当我尝试通过调用acquireTokenSilent来获取令牌并尝试使用此令牌来调用API时,会出现401错误。

如何从angular应用程序中获取正确的JTW令牌?

enter image description here

2 个答案:

答案 0 :(得分:1)

请确保您已授予您的客户端应用程序的权限以及在api应用程序中公开的权限,请遵循此doc

然后在consentScopes中,使用您的api的api范围,您可以在API应用的Application ID URL页中找到Expose an API,例如类似于api://xxxxxxxxxxxxxxx/api_usage

consentScopes: [
        '<Application ID URL>/scope'
      ],

获得令牌后,将["<Application ID URL>/scope"]用作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);
});

有关更多详细信息,请参阅Tutorial: Sign in users and call the Microsoft Graph API from an Angular single-page application。在此文档中,它调用了MS Graph,以调用您自己的api,更改了作用域,它应该可以工作。

答案 1 :(得分:0)

在会话已经过期或在宽限期内的情况下,您可能无法使用acquiredTokenSilentAsync获取令牌。当无法获取令牌时,调用acquireTokenAsync将重定向用户以输入密码进行登录。

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
        });
    });