【问题标题】:Calling an Azure AD secured Web API from Angular Frontend从 Angular 前端调用受 Azure AD 保护的 Web API
【发布时间】:2019-12-03 10:59:36
【问题描述】:

我目前正在开发一个 Angular 前端,它使用 MSAL 对用户进行身份验证。此前端应调用受 Azure Active Directory 保护的 Web-API(也托管在 Azure 中)。

虽然我很容易设法使用 Angular 和 MSAL,获得了一个令牌并成功调用 Graph/me 作为测试,但我无法让 API 调用正常工作,我总是收到 401。

我正在使用以下设置:

  1. 带 MSAL 的 Angular 前端
    我在 AAD 中创建了一个应用程序,为它授予 MS Graph 的 User.Read 权限,将 ID 复制到 MSAL 代码中,并且按照文档使用 MSAL 拦截器调用 Graph API 非常容易。
  2. Web-API
    我在 .NET 核心中创建了一个 web-api,只是在 GET 中返回了一些演示数据。我将 API 发布到 azure Web 应用程序(https://myappurl.azurewebsites.net/api/test,从 Angular 或 Postman 调用它没有问题
  3. 授权
    使用 Azure 门户,在 App Web 设置中,我使用 Azure Active Directory 激活了 Web 服务身份验证。作为所需的应用程序,我将在第 1 步中使用的同一个应用程序用于前端。

此时我无法再调用我的 API,总是收到 401。 我从 Angular 代码中解析出 JWT 令牌,并尝试使用 Authorization: Bearer eyJ0xxxxx headers, still 401 进行邮递员调用。

我想,通过“登录”我的前端,我应该能够使用令牌来识别自己的 API 调用,因为它使用相同的 app-id,但不知何故我认为我把它弄混了。我查看了很多文档,但由于 Azure 门户中的应用注册更改,它大多已经过时了。

export const protectedResourceMap:[string, string[]][]=[['https://graph.microsoft.com/v1.0/me', ['user.read']] ];
MsalModule.forRoot({
      clientID: "my-client-id",
      redirectUri: "http://localhost:4200/profile",
      postLogoutRedirectUri: "http://localhost:4200/bye",
      authority: "https://login.microsoftonline.com/my-tenant-id",
      validateAuthority: true,
      cacheLocation : "localStorage",
      navigateToLoginRequestUrl: true,
      popUp: false,
      consentScopes: [ "user.read" ],
      unprotectedResources: ["https://www.microsoft.com/en-us/"],
      protectedResourceMap: protectedResourceMap,
      correlationId: '1234',
      piiLoggingEnabled: true
    }),

我需要将 webAPI 添加到 Angular 中的受保护资源吗?我是否需要额外的应用程序来保护 API,然后允许我的前端应用程序访问后端应用程序?阅读所有可用的文章让我更加困惑。

【问题讨论】:

  • 我也有同样的情况。提供的答案对您有帮助吗?我有我公开的 api 的范围 url,但我不知道在我的前端哪里指定它......你把它添加到 consentScopes 了吗?或protectedResourceMap?非常感谢您的帮助!

标签: azure api authentication asp.net-core-webapi msal


【解决方案1】:

在您的 azure 注册应用程序中,转到“公开 api”,复制范围 url 并将此值设置为您 loginRequest 中的范围

var loginRequest = {
                   scopes: ["api://aa059cdd-1f53-4707-82a8-fdf7bd6c2859/Test"] 
               };


msalInstance.loginPopup(loginRequest)
.then(response => {
    // handle response
})
.catch(err => {
    // handle error
});

【讨论】:

    猜你喜欢
    • 2020-02-19
    • 2017-11-02
    • 1970-01-01
    • 2018-11-07
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 2014-10-29
    相关资源
    最近更新 更多