2014-08-30 85 views
4

我有一个项目同时包含一个API和一个包含一些Web窗体的区域。
最近API的Token端点开始抛出CORS错误,我找不出为什么或者如何解决它。为ASP API令牌请求启用CORS

我已经更新了Startup.Auth.cs与文件:app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

也尝试添加config.EnableCors(new EnableCorsAttribute("*", "*", "GET,POST"));到WebApiConfig.cs文件。

这些都没有添加所需的'Access-Control-Allow-Origin'标头。 (如果两者同时执行,我确实会得到不同的错误,所以我知道这不是问题。)

是否存在项目中的另一个位置,我需要设置该位置以允许CORS请求身份验证令牌?

回答

1

好的,发现了问题。

首先,我的测试工具指向错误的位置,所以我所做的任何更改都没有效果,我的断点也没有被击中。我的错。

其次,终于得到了我工作的配置是有下面的代码:

ApplicationOAuthProvider.GrantResourceOwnerCredentials: 
var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin"); 
if (allowedOrigin == null) allowedOrigin = "*"; 


WebApiConfig.Register: 
config.EnableCors(new EnableCorsAttribute("*", "*", "GET,POST")); 

我希望这可以帮助任何其他人与CORS和武士刀/ OWIN中间件挣扎。

+0

+1这帮了我很多! – JMK 2014-11-17 00:04:22

2

我不得不在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); 
+0

+1第二种方法是快速修复。你只需要添加'Microsoft.Owin.Cors' nuget包。关于SO的另一个非常有用的线索http://stackoverflow.com/questions/20079813/how-to-make-cors-authentication-in-webapi-2 – 2016-04-01 11:24:17

1

在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>