问题描述
环境
- Angular 5前端
- ASP.NET WebAPI 2
- WebAPI上的AzureAD身份验证
配置
- WebAPI已为所有人启用(***)CORS
- AzureAD是启用的OAuthImplicitFlow
- Angular和WebAPI托管在同一IIS中,不同的端口
挑战
直接通过浏览器调用WebAPI时,AzureAD身份验证质询正常,并且调用获得授权.但是,当Angular调用WebAPI时,AzureAD的身份验证挑战会引发CORS问题.
When WebAPI is called directly via browser, AzureAD auth challenge works fine and call gets authorized. However when Angular calls the WebAPI, AzureAD's auth challenge throws a CORS issue.
Angular应用程序不会直接(通过adal-angular)调用Azure,其应仅通过WebAPI进行调用.Angular应用程序已成功在WebAPI上成功调用了不受保护的GET/POST函数,因此Angular-WebAPI连接很好.
The Angular app will not call Azure directly (via adal-angular), its supposed to call via WebAPI only.Angular app is successfully calling non-protected GET/POST functions on WebAPI successfully, so Angular-WebAPI connectivity is fine.
(更新1 Angular APP调用ADAL-ANGULAR向Azure进行身份验证并获得令牌,然后将相同的令牌作为承载传递给WebAPI )
有人在想我在这里缺少什么吗?可以根据需要提供任何特定的代码/配置.
Any thoughts what I am missing out here ? Any specific code/configuration can be made available as required.
代码
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;
}
角度
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;
}
错误消息
推荐答案
这不是它的工作方式. Http客户端将从不重定向您到页面(在您的情况下为AAD登录页面).它仅从资源中检索内容/将内容发送到资源.您可以使用 window.location.replace()执行重定向,但这可能不是您想要的(令牌不会返回您的角度应用程序).
This is not how it works. The Http Client will never redirect you to a page (in your case the AAD Signin-Page). It only retrieves / sends content from / to a resource. You can perform a redirect using window.location.replace() but thats probably not what you want (the token will not get back to your angular application).
您需要选择一个 Active Directory身份验证库,例如 adal-js 或 MSAL (您将找到两者的Angular NPM软件包),使用AAD设置配置组件.然后,您可以对Angular客户端的登录进行挑战,并为您的API请求 access_token .现在,您必须针对(保护)API发出的每个请求,在授权HTTP标头"中传递access_token.
You need to choose a Active Directory Authentication Library like adal-js or MSAL (you will find Angular NPM packages for both) and configure the component with your AAD settings. Then you can challange the signin from your Angular client and request an access_token for your API. Now you have to pass the access_token in the Authorization HTTP Header with each request you make against your (protect) API.
请注意,您应该在AAD中创建另一个代表Angular UI的应用程序,并授予该应用程序对您的API的访问权限.
Note that you should create another Application in the AAD that represents your Angular UI and grant that app access to your API.
这篇关于Angular 5调用AzureAD保护的WebAPI导致CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!