angular - 为什么我的 API 管理不使用 AD B2C 自动化我的应用程序?

标签 angular typescript azure-ad-b2c azure-api-management

我正在开发一个使用 AD B2C 作为 OpenID Connect 提供商的云应用程序。

在我的配置环境下:

广告 B2C

在我的 AD B2C 中,我创建了两个应用程序:

  • DeveloperPortal - 这用于在开发人员门户中配置授权。
  • MyClient - 这用于在内部配置授权。

API 网关

我创建了一个 API Management .在 API 导入之后,我添加了如下一项政策:

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
            <openid-config url="https://login.microsoftonline.com/{myTenantAzureId}/.well-known/openid-configuration?p={myPolicies}" />
</validate-jwt>

我的客户

我的客户端是 Angular 4 应用程序。我正在使用 MSAL.js微软官方库。

这是我的授权服务 TypeScript 类:

import { Injectable } from '@angular/core';
declare var bootbox: any;
declare var Msal: any;

@Injectable()
export class MsalService {
  public access_token: string;
  private logger = new Msal.Logger(this.loggerCallback, { level: Msal.LogLevel.Verbose });

  tenantConfig = {
    tenant: "{myTenant}.onmicrosoft.com",
    clientID: '{MyClientClientId}',
    signUpSignInPolicy: "{myPolicies}",
    b2cScopes: ["openid"]
  };

  options = {
    logger: this.logger,
    postLogoutRedirectUri: window.location.protocol + "//" + window.location.host
  }

  //authority = null;
  authority = "https://login.microsoftonline.com/tfp/" + this.tenantConfig.tenant + "/" + this.tenantConfig.signUpSignInPolicy;


  clientApplication = new Msal.UserAgentApplication(
    this.tenantConfig.clientID,
    this.authority,
    this.authCallback,
    this.options
  );

  public login(callback: Function): void {
    var _this = this;
    this.clientApplication.loginPopup(this.tenantConfig.b2cScopes).then(function (idToken: any) {
      _this.clientApplication.acquireTokenSilent(_this.tenantConfig.b2cScopes).then(
        function (accessToken: any) {
          _this.access_token = accessToken;
          localStorage.setItem("access_token", accessToken);
          if (callback) {
            callback(accessToken);
          }
        }, function (error: any) {
          _this.clientApplication.acquireTokenPopup(_this.tenantConfig.b2cScopes).then(
            function (accessToken: any) {
              _this.access_token = accessToken;
              console.log(accessToken);
            }, function (error: any) {
              bootbox.alert("Error acquiring the popup:\n" + error);
            });
        })
    }, function (error: any) {
      console.log(error);
      bootbox.alert("Error during login:\n" + error);
    });
  }

  public logout(callback: Function): void {
    this.clientApplication.logout();
    if (callback) {
      callback();
    }
  }

  private loggerCallback(logLevel, message, piiLoggingEnabled) {
    console.log(message);
  }
  private authCallback(errorDesc: any, token: any, error: any, tokenType: any) {
    if (token) {
    }
    else {
      console.error(error + ":" + errorDesc);
    }
  }
}

问题

如果我尝试使用带有访问 token 的授权 header 调用一个 API 管理的 API,我会收到此错误:

{ "statusCode": 401, "message": "Unauthorized. Access token is missing or invalid." }

但如果我尝试直接通过 Developer Portal 访问,我可以成功调用相同的 API。 enter image description here

为什么我的 API Manager 不授权我的应用程序?

非常感谢

最佳答案

我认为上述错误的发生是因为 API 网关无法识别从 Angular 客户端传递的访问 token 的 aud(观众)声明。

上面的场景类似于"Azure AD B2C: Call a .NET web API from a .NET web app"其中 Angular 客户端是 Web 应用程序,API 网关是 Web API。

我推荐你:

1) Create an Azure AD B2C app代表 API 网关。输入此应用程序的应用程序 ID URI 以标识 API 网关。

2) Add one or more permission scopes到此网关应用程序和/或保留 user_impersonation 的默认权限范围。

3) Create an Azure AD B2C app代表 Angular 客户端。您已经创建了这个客户端应用程序。

4) Grant access by the client app to the gateway app以便客户端应用程序可以获得访问 token 以代表登录用户调用网关应用程序。

5) Update the validate-jwt policy使用网关应用程序的应用程序 ID。

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">  
  <openid-config url="https://login.microsoftonline.com/tfp/{tenant}/{policy}/v2.0/.well-known/openid-configuration" />
  <audiences>
    <audience><!-- Paste the app ID for the gateway app --></audience>
  </audiences>
</validate-jwt>

6) 在 tenantConfig.b2cScopes 数组中包含在第 2 步中添加的要颁发给客户端应用程序的任何权限范围。

关于angular - 为什么我的 API 管理不使用 AD B2C 自动化我的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49576617/

相关文章:

javascript - Angular 2 和 FireBase 消息传递 - 无法注册

javascript - 带有身份验证登录页面的 angular2 应用程序

angular - 测试在 Angular 7 中向 <body> 添加类

node.js - Typescript 编译器选择错误的重载

azure-ad-b2c - 如何使用 B2C 自定义策略将登录限制到指定的 IP 地址范围

azure - 在 azure b2c 用户流程中使用已注册的电子邮件时,向用户显示未定义的错误

javascript - Angular 2 : Access Cookie after Creation

angular - 如何从服务器响应 Angular 2 中读取内容配置 header

typescript - 在 type-graphql 中传递 typescript 类型问题

azure - 用于访问 Azure 服务的临时安全凭证