获取授权令牌以调用 API

Get Authorization token to call API

我正在尝试调用由 following these directions 创建的 API,我已经到了可以使用 JWT 令牌从 Developer Portal 调用 API 的地步。

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

目前,angular 应用程序的用户在 Active Directory 中(在设置 API 的说明中使用的同一个 AD)。登录过程通过 MSAL library. When I try to get the token by calling acquireTokenSilent 完成并尝试使用此令牌调用 API,我收到 401 错误。

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

在会话已过期或在宽限期内的情况下,您可能无法使用 acquireTokenSilentAsync 获取令牌。当获取令牌失败时,调用 acquireTokenAsync 会将用户重定向到 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
        });
    });

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

然后在 consentScopes 中,使用 api 的 api 范围,您可以在 Expose an API 页面中找到 Application ID URL 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,更改范围,它应该可以工作。