Web 的 AuthorizeAttribute API(ASP.NET 核心 2)

AuthorizeAttribute for Web API (ASP.NET Core 2)

我想将 AuthorizeAttribute 用于我的 Web API 方法。 但是当用户未被授权方法 returns Login-View 而不是简单的 401-status-code.

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{           
    // Another code.
    services.AddDefaultIdentity<User>(opt => {})
    .AddEntityFrameworkStores<MyDbContext>();
    // Another code.
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Another code.
    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "api/{controller}/{action=Index}/{id?}");
    });

    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
            spa.UseReactDevelopmentServer(npmScript: "start");
        }
    });
    // Another code.
}

SimpleController.cs:

[Route("api/[controller]")]
public class SimpleController : Controller
{
    [Authorize]
    [HttpGet("{id}")]
    public int Index(int Id)
    {
        return Id;
    }
}

在 ASP.NET MVC 5 中我们有两个 AuthorizeAttribute:

  1. System.Web.Http.AuthorizeAttribute - 用于网络 API.
  2. System.Web.Mvc.AuthorizeAttribute - 用于有视图的控制器。

但是ASP.NET Core 2.0 只有一种属性——用于带视图的控制器。 我需要做什么才能获取状态代码 (401、403) 而不是视图?

ASP.NET Core Identity 使用 cookie 身份验证,因此您可以覆盖 CookieAuthenticationOptions.Events 以使其根据需要工作。 Identity为此提供ConfigureApplicationCookie配置方法

services.ConfigureApplicationCookie(options =>
{
    //this event is called when user is unauthorized and is redirected to login page
    options.Events.OnRedirectToLogin = context =>
    {
        context.Response.StatusCode = 401;

        return Task.CompletedTask;
    };
});