【问题标题】:How to check whether request is going to an method with [Authorize] attribute?如何检查请求是否发送到具有 [Authorize] 属性的方法?
【发布时间】:2019-05-23 22:54:46
【问题描述】:

我有 WebAPI Controller 派生自 BaseController 派生自 AspNetCore's Controller

每当他进入需要[Authorize]的端点时,我想从数据库中加载User

这是我的代码,其中if 中的条件是伪代码,因为我不知道如何检查此请求是否需要授权

public class DefaultController : Controller
{
    protected readonly DatabaseContext _context;
    protected readonly User _user;

    public DefaultController(DatabaseContext context)
    {
        _context = context;

        if (HttpContext.Request.RequiresAuthorization) // pseudo code
        {
            var id = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            _user = _context.Users.Find(id);
        }
    }
}

基本上我想避免在每个请求上加载用户,即使他不需要授权并且不能在那里登录。

是否有可能实现某种“全局”,所以 BaseController 是所有其他控制器派生的?

【问题讨论】:

  • 为什么不在控制器类或特定操作上使用 [Authorize] 属性?
  • @chrillelundmark 这很有意义,但我必须为同一件事编写例如两个控制器。我会考虑,因为它很简单,谢谢!

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

您可以使用MvcOptions.Filters 全局注册您的授权过滤器。

Startup.cs

public void ConfigureServices(IServiceCollection services)
 { 
      services.AddMvc(options =>
      {
           options.Filters.Add(typeof(AuthorizationFilter));
      });
 }

由于您需要连接数据库,我建议您通过扩展 IAsyncAuthorizationFilter 创建自定义 AuthorizationFilter

public class AuthorizationFilter : IAsyncAuthorizationFilter
{
    //use constructor to inject required dependencies

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
         //Move your custom logic here
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-05
    • 2011-07-04
    • 2019-11-18
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多