代码之家  ›  专栏  ›  技术社区  ›  Palindromer

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

  •  0
  • Palindromer  · 技术社区  · 7 年前

    我想用 AuthorizeAttribute 对于我的Web API方法。 但当用户未被授权时,方法返回登录视图,而不是简单的401状态代码。

    启动.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.
    }
    

    单工控制器.cs:

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

    在ASP.NET MVC 5中,我们都有 授权属性 :

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

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

    0 回复  |  直到 7 年前
        1
  •  3
  •   Alexander    7 年前

    ASP.NET核心标识使用cookie身份验证,因此可以重写 CookieAuthenticationOptions.Events 让它按你的需要工作。身份提供 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;
        };
    });