我有一个项目,它有一个API和一个包含一些web表单的Area
最近API的Token端点开始抛出CORS错误,我不知道为什么或如何修复它
我已将Startup.Auth.cs文件更新为:app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
还尝试将config.EnableCors(new EnableCorsAttribute("*", "*", "GET,POST"));
添加到WebApiConfig.cs文件中。
这两个都没有添加所需的"Access Control Allow Origin"标头。(如果同时实现这两个功能,我确实会遇到不同的错误,所以我知道这不是问题所在。)
项目中是否还有其他位置需要设置以允许CORS请求身份验证令牌?
我必须在ApplicationOAuthProvider.cs/GrantResourceOwnerCredentials中这样才能工作。前三行仅用于参考点,添加了"context.OwinContext"行以使其工作。
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
**context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:24589" });**
如果您想在不同的接入点单独配置并允许CORS,请使用以上内容。如果您希望允许应用程序范围,则可以修改ApplicationOAuthProvider.cs/ConfigureAuth,如下所示。任何一种方法都有效。
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
好的,找到问题了。
首先,我的测试背带指向了错误的位置,所以我所做的任何更改都没有效果,我的断点也没有被击中。我的坏。
第二,最终让我工作的配置是有以下代码:
ApplicationOAuthProvider.GrantResourceOwnerCredentials:
var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
if (allowedOrigin == null) allowedOrigin = "*";
WebApiConfig.Register:
config.EnableCors(new EnableCorsAttribute("*", "*", "GET,POST"));
我希望这能帮助其他正在使用CORS和Katana/OWIN中间件的人。
在WebApiConfig.cs中启用CORS后,您还应该配置web.config以同时启用CORS。它在我的应用程序中起作用:
<system.webServer>
<!--Enbale CORS-->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://yourwebsite" />
</customHeaders>
</httpProtocol>
<modules>
...
</modules>
</system.webServer>
我也很挣扎,花了大约5个小时,终于找到了解决方案。
技术:Asp.net框架
解决方案:需要安装";微软Owin.Cors"
并将下面的行添加到";Startup.Auth.cs/ConfigureAuth()"方法
app.UseCors(CorsOptions.AllowAll);
我们不想在任何地方添加任何内容,这已经足够了,对我来说也很好。
我从这里得到了答案:从Angular2的web API2获取令牌会导致CORS问题或为空