环境
- Angular 5 前端
- ASP.NET WebAPI 2
- WebAPI 上的 AzureAD 身份验证
配置
- WebAPI 已为所有人启用 CORS (***)
- AzureAD 已启用 OAuthImplicitFlow
- Angular 和 WebAPI 托管在同一 IIS 中,但端口不同
挑战
当通过浏览器直接调用 WebAPI 时,AzureAD 身份验证质询工作正常并且调用获得授权。然而,当 Angular 调用 WebAPI 时,AzureAD 的身份验证挑战会引发 CORS 问题。
Angular 应用不会直接调用 Azure(通过 adal-Angular),它应该仅通过 WebAPI 调用。 Angular 应用程序成功调用 WebAPI 上不 protected GET/POST 函数,因此 Angular-WebAPI 连接正常。
(更新 1 Angular 应用调用 ADAL-ANGULAR 向 Azure 进行身份验证并获取 token ,然后将相同的 token 作为承载传递给 WebAPI)
有什么想法我在这里错过了什么吗?可以根据需要提供任何特定的代码/配置。
代码
WebAPI
[HttpGet]
[Authorize]
[Route(ApiEndPoint.AzureAD.GetMyProfile)]
public async Task<ADUser> GetUserProfile()
{
ADUser user = null;
GraphFacade graphFacade = new GraphFacade(this.graphServiceClient);
user = await graphFacade.GetMyProfileDetails();
return user;
}
Angular
Authenticate(): Observable<any> {
this.authServerUrl = "https://localhost:44371/"; // This is where WebAPI is running
let httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
let authRequest = this._http.get<any>(this.authServerUrl + '/api/aduser/profile', httpOptions);
return authRequest;
}
错误消息
Failed to load https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=fba45f7b : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
最佳答案
这不是它的工作原理。 Http 客户端将永远不会将您重定向到页面(在您的情况下为 AAD 登录页面)。它仅从资源检索内容/向资源发送内容。您可以使用 window.location.replace() 执行重定向,但这可能不是您想要的( token 不会返回到您的 Angular 应用程序)。
您需要选择一个 Active Directory 身份验证库,例如 adal-js 或 MSAL(您将找到两者的 Angular NPM 包)并且使用您的 AAD 设置配置组件。然后,您可以从 Angular 客户端挑战登录并为您的 API 请求 access_token。现在,您必须在针对(保护)API 发出的每个请求中传递授权 HTTP header 中的 access_token。
请注意,您应该在 AAD 中创建另一个应用程序来代表您的 Angular UI,并授予该应用程序对您的 API 的访问权限。
关于Angular 5 调用 Azure AD protected Web API 导致 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50577866/