问题描述
我有一个带有 AngularJS 前端和 Web Api 2 后端的 Web 应用程序,它使用承载令牌进行身份验证.
I have a web-app with an AngularJS front-end and a Web Api 2 back-end, and it uses bearer-tokens for authentication.
在 FireFox 中一切正常IE,但使用 Chrome 时,我的初始登录请求有时是预检.
All is well in FireFox & IE, but with Chrome, my initial login request is SOMETIMES pre-flighted.
这是来自 AngularJS 服务的调用:
Here's the call from the AngularJS service:
$http.post(http://localhost:55483/token
, data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) { ... });
$http.post(http://localhost:55483/token
, data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) { ... });
预检请求因Allow-Access-Control-Origin"错误而被退回.
The preflight request gets kicked back with an "Allow-Access-Control-Origin" error.
但是,如果我再次单击登录"按钮(从而重新发送上述请求),则一切正常.
However, if I click the Login button again (thereby re-sending the above request) all is well.
知道如何预防/捕获/处理这种情况吗?
Any idea on how to prevent/trap/handle this?
PS:我使用 LOC
PS: I use the LOC
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
在 ApplicationOAuthProvider.cs
文件中,将 CORS 允许标头放在/Token 请求上,这在 IE、FireFox 和有时在 Chrome 中工作正常.
in the ApplicationOAuthProvider.cs
file to put the CORS allow-header on the /Token request, which works fine in IE, FireFox and sometimes in Chrome.
推荐答案
以下为花式评论:
The below is Fancy comment:
在 LeftyX 6 月 29 日发布的帖子的帮助下解决了这个问题:
- 移动这个 LOC app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
到Startup.Auth.cs 的 ConfigureAuth 方法中的第一行.
- 那么,删除此 LOCcontext.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",new[] { "*" });
来自 GrantResourceOwnerCredentials() 方法ApplicationOAuthProvide.cs.
Preflight CORS-请求他们获取处理得当,然后真正的请求通过
谢谢老兄,你救了我一整天.
因为它发生在很多人身上,我把你的评论带到回答框,让其他人可以看到.
我不想为此投票.请改为评论我的回答
谢谢
Thank man, you save my whole day.
Cause it happens for many guys, I bring your comment to answer box for other guys can see it.
I don't want to get vote up for this. Please comment on my answer instead
Thank you
这篇关于Web Api 2 Preflight CORS 请求承载令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!