【问题标题】:Get Authorization token to call API获取授权令牌以调用 API
【发布时间】:2020-08-06 20:32:57
【问题描述】:

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

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

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

如何从 Angular 应用中获取正确的 JTW 令牌?

【问题讨论】:

    标签: angular azure azure-api-management msal


    【解决方案1】:

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

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

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

    获得令牌后,将["&lt;Application ID URL&gt;/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,更改范围,它应该可以工作。

    【讨论】:

      【解决方案2】:

      如果会话已过期或在宽限期内,您可能无法使用 acquireTokenSilentAsync 获取令牌。当获取token失败时,调用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
              });
          });
      

      【讨论】:

      • 嗨 Joko,感谢您的建议,但是,我在登录后立即收到 401 错误。通常,令牌不会立即过期。欢迎使用 StackOverflow!
      猜你喜欢
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      相关资源
      最近更新 更多