我目前正在开发一个 Angular 前端,它使用 MSAL 来对用户进行身份验证。该前端应调用 Web-API(也托管在 Azure 中),该 API 由 Azure Active Directory 保护。
虽然我轻松地设法使用 Angular 和 MSAL,获取令牌并成功调用 Graph/me 作为测试,但我无法使 API 调用正常工作,我总是收到 401。
我正在使用以下设置:
- 带有 MSAL 的 Angular 前端
我在 AAD 中创建了一个应用程序,为其授予了 MS Graph 的 User.Read 权限,将 ID 复制到 MSAL 代码中,并按照文档使用 MSAL 拦截器调用 Graph API 非常简单。
- Web-API
我在 .NET core 中创建了一个 web-api,只是在 GET 中返回一些演示数据。我将 API 发布到了 azure Web 应用程序 (https://myappurl.azurewebsites.net/api/test https://myappurl.azurewebsites.net/api/test,从 Angular 或 Postman 调用它没有问题
- Auth
使用 Azure 门户,在应用程序 Web 设置中,我激活了 Azure Active Directory 的 Web 服务身份验证。作为所需的应用程序,我将与步骤 1 中使用的相同的应用程序放置在前端。
此时我无法再调用我的 API,总是收到 401。
我从 Angular 代码中解析出 JWT 令牌,并尝试使用 Authorization: Bearer eyJ0xxxxx 标头进行邮递员调用,仍然是 401。
我想,通过“登录”我的前端,我应该能够使用令牌来识别自己的 API 调用身份,因为它使用相同的应用程序 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,然后允许我的前端应用程序访问后端应用程序?阅读所有可用的文章让我更加困惑。