Web API的AuthorizeAttribute(ASP.NET Core 2) [英] AuthorizeAttribute for Web API (ASP.NET Core 2)

查看:105
本文介绍了Web API的AuthorizeAttribute(ASP.NET Core 2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对我的Web API方法使用 AuthorizeAttribute .但是,当用户未获得授权时,方法将返回Login-View而不是简单的401状态代码.

I want to use AuthorizeAttribute for my Web API methods. But when user is not authorized method returns Login-View instead simple 401-status-code.

Startup.cs:

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:

SimpleController.cs:

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

在ASP.NET MVC 5中,我们都有 AuthorizeAttribute :

In ASP.NET MVC 5 we have both AuthorizeAttribute:

  1. System.Web.Http.AuthorizeAttribute -用于Web API.
  2. System.Web.Mvc.AuthorizeAttribute -用于具有视图的控制器.
  1. System.Web.Http.AuthorizeAttribute - which is used for the web API.
  2. System.Web.Mvc.AuthorizeAttribute - which is used for controllers with views.

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

But ASP.NET Core 2.0 has only one kind of attribute - for controllers with views. What do I need to do to get status-codes (401, 403) instead views?

推荐答案

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

ASP.NET Core Identity uses cookie authentication and therefore you can override CookieAuthenticationOptions.Events to make it work as you need. Identity provides ConfigureApplicationCookie configuration method for this.

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;
    };
});

这篇关于Web API的AuthorizeAttribute(ASP.NET Core 2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆