CORS在使用OWIN身份验证的web api中无效

Bin*_*ose 18 asp.net-mvc cors asp.net-web-api owin katana

在我的应用程序中,我使用带有基于令牌的身份验证的web api和CORS支持,但是当客户端请求令牌时,由于CORS发生错误(跨源请求被阻止:同源策略不允许在(我的站点)读取远程资源这可以通过将资源移动到同一域或启用CORS来解决.)

我已经配置了CORS支持所需的一切(我想是这样).在这里我的配置

Owin开始上课

   public class Startup
    {
        public void Configuration(IAppBuilder app)
        {


            var config = new HttpConfiguration
            {
                DependencyResolver = new StructureMapWebApiDependencyResolver(container)

            };


            WebApiConfig.Register(config);  // registering web api configuration
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);  // cors for owin token pipeline
            app.UseWebApi(config);
            ConfigureOAuth(app);


        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            var oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions()
            {

                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };
            // Token Generation
            app.UseOAuthAuthorizationServer(oAuthAuthorizationServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }
    }
Run Code Online (Sandbox Code Playgroud)

和我的webapi配置

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.EnableCors();  // Corse support for Web api
            config.MapHttpAttributeRoutes(); // attribute based urls

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

        }
    }
Run Code Online (Sandbox Code Playgroud)

这里配置在web.config中

<system.webserver>
 <httpProtocol>
      <customHeaders>
        <!-- Adding the following custom HttpHeader will help prevent CORS from stopping the Request-->
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
      </customHeaders>
    </httpProtocol>
</system.webserver>
Run Code Online (Sandbox Code Playgroud)

来自mozilla的我的请求标题

Accept  application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length  67
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
Host    talenterp
Origin  http://192.168.1.11:85
Referer http://192.168.1.11:85/
User-Agent  Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0
Run Code Online (Sandbox Code Playgroud)

应用程序的URL是

服务器应用程序(应该支持CORS)

{http://talenterp}
Run Code Online (Sandbox Code Playgroud)

令牌终点:

{http://talenterp/token}
Run Code Online (Sandbox Code Playgroud)

客户端应用

{http://talentmvc:85}
Run Code Online (Sandbox Code Playgroud)

NB:我已经补充了

context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
Run Code Online (Sandbox Code Playgroud)

在AuthorizationServerProvider的GrantResourceOwnerCredentials()方法中

Elg*_*des 59

确保你只有

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

已配置,而不是 Global.asax或WebApiConfig中的旧样式'config.EnableCors()'.此外:将上述语句作为owin Startup类中的第一个语句.是的,这确实有所作为,稍后设置它也会导致cors无法正常工作.

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        ... etc
Run Code Online (Sandbox Code Playgroud)

  • 本文介绍如何提供自定义CORS策略:http://benfoster.io/blog/aspnet-webapi-cors (3认同)
  • 现在这应该被标记为正确的答案.谢谢! (3认同)
  • 将UseCors调用移动到Configuration方法中的第一个,它解决了我们的405问题.Postman工作得很好,但是从Chrome开始就是405. (2认同)
  • 将该行向上移动到Configuration方法的顶部也是我的.谢谢! (2认同)
  • 一次又一次@Pogrindis。某种“stackenfreude”,你为自己的不幸而高兴,因为它会带你回到你自己完全忘记的 stackoverflow 答案。令人惊讶的是,这种情况发生的频率如此之高。 (2认同)

Dad*_*uco 5

OWIN和Microsoft.AspNet.WebApi.Cors是两个独立的库,每个库都需要单独配置.

禁止在OWIN中使用CORS:

public void Configuration(IAppBuilder app)
{
        //app.UseCors(CorsOptions.AllowAll);
Run Code Online (Sandbox Code Playgroud)

找到GrantResourceOwnerCredentials方法并将Access-Control-Allow-Origin添加到上下文中,以便在完成身份验证后返回一个调用时,浏览器会找到标头并接受它.

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost" });
Run Code Online (Sandbox Code Playgroud)

现在将Nuget的Microsoft.AspNet.WebApi.Cors包安装到您的webapi项目中,并将其添加到Register方法

public static void Register(HttpConfiguration config)
{
        var cors = new EnableCorsAttribute("http://localhost, ", "accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS");

        config.EnableCors(cors);
Run Code Online (Sandbox Code Playgroud)

这样做对我来说.