带有Authorize属性的ASP.NET 5 beta8 CORS无效

时间:2015-10-23 10:04:11

标签: c# cors asp.net-core

在beta7中,CORS能够设置如下:

// in the ConfigurationServices
services.AddMvc();
services.ConfigureCors(options =>
{
    // set cors settings...
});

//...
// in the Startup.Configure method
app.UseCors();
app.UseMvc();

它就像一个魅力,但beta8打破了它。我发现了这个问题:Why Cors doesn't work after update to beta8 on ASP.NET 5?,并修改如下:

// in Startup.ConfigureServices method
services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", builder =>
    {
        // allow them all
        builder.AllowAnyHeader();
        builder.AllowAnyMethod();
        builder.AllowAnyOrigin();
        builder.AllowCredentials();
    });
});
services.AddMvc();

//...
// in the Startup.Configure method
app.UseMvc();

//...
// in the Controller
[EnableCors("CorsPolicy")]
public IActionResult Get()
{
    return OK();
}

是的它再次起作用,但当我添加[Authorize("Bearer")]时,控制器通过ajax调用返回401 Unauthorized for OPTIONS请求。这是HTTP请求和响应。

[请求]

OPTIONS https://api.mywebsite.net/ HTTP/1.1
Accept: */*
Origin: https://myanotherwebsite.net
Access-Control-Request-Method: GET
Access-Control-Request-Headers: accept, authorization
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko
Host: api.mywebsite.net
Connection: Keep-Alive
Cache-Control: no-cache

[响应]

HTTP/1.1 401 Unauthorized
Content-Length: 0
Server: Microsoft-IIS/8.0
WWW-Authenticate: Bearer
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=...;Path=/;Domain=api.mywebsite.net
Date: Fri, 23 Oct 2015 09:56:34 GMT

如何在ASP.NET 5 beta8中启用带[Authorization]属性的CORS?

修改 我能够使用默认的ASP.NET MV C6模板(beta 8)重现此问题。 当我用[EnableCors][Authorize]装饰控制器或方法时,它返回401 Unauthorized(或302重定向到登录页面)。

EDIT2 事实证明,这是我的一个愚蠢的错误。我回答了自己的问题。

1 个答案:

答案 0 :(得分:2)

好的,这是我的愚蠢错误。我在Microsoft.AspNet.Mvc.CorsMicrosoft.AspNet.Cors之间感到困惑。

前一个是关于OWIN中间件,另一个是关于Mvc过滤器。我没有在Microsoft.AspNet.Cors中添加Project.json,也未在app.UseCors()中添加Configures()

AddCors()中的ConfigureServices()UseCors()中的Configure()都需要一起工作。

这可能是CORS的基本设置。

(在Project.json

"dependencies": {
  ...
  "Microsoft.AspNet.Cors": "6.0.0-beta8",
  "Microsoft.AspNet.Mvc.Cors": "6.0.0-beta8",
  ...
}

(在Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy", builder =>
        {
            // ...build cors options...
        });
    });
    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseIISPlatformHandler();
    app.UseStaticFiles();
    app.UseCors("CorsPolicy");
    app.UseMvc();
}

或者,这个:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseIISPlatformHandler();
    app.UseStaticFiles();
    app.UseCors(builder =>
    {
        // ...default cors options...
    });
    app.UseMvc();
}

希望没有人像我一样犯愚蠢的错误。