简体   繁体   English

ASP.net 内核中 ActionFilterAttribute 的替代方案

[英]Alternative to ActionFilterAttribute in ASP.net core

I am trying to authenticate users in my asp.net core 2.2 application.我正在尝试在我的 asp.net 核心 2.2 应用程序中对用户进行身份验证。 This is how we use to do it in asp.net web api using .net 4.5这就是我们在 asp.net web api 中使用 Z2D50972FCECD57612989Z5450 的方法。

public class AuthFilter : ActionFilterAttribute, IActionFilter
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
          //based on certain condition
filterContext.Result = new UnauthorizedResult();
    } 

}

I am looing to achieve same in asp.net core 2.2.我想在 asp.net 核心 2.2 中实现相同的目标。 Only change is, I need to implement this logic only for few routes.唯一的变化是,我只需要为少数路线实现这个逻辑。 So basically I need to check the route first and then authenticate users only for those roytes .所以基本上我需要先检查路线,然后只为那些 roytes 验证用户 This is what I found so far:这是我到目前为止发现的:

public class CustomAuthenticationSchemeProvider : AuthenticationSchemeProvider
{
    private readonly IHttpContextAccessor httpContextAccessor;

    public CustomAuthenticationSchemeProvider(
        IHttpContextAccessor httpContextAccessor,
        IOptions<AuthenticationOptions> options)
        : base(options)
    {
        this.httpContextAccessor = httpContextAccessor;
    }

    private async Task<AuthenticationScheme> GetRequestSchemeAsync()
    {
        var request = httpContextAccessor.HttpContext?.Request;
        if (request == null)
        {
            throw new ArgumentNullException("The HTTP request cannot be retrieved.");
        }

        // For API requests, use authentication tokens.
        if (request.Path.StartsWithSegments("/api"))
        {
            return await GetSchemeAsync(OAuthValidationDefaults.AuthenticationScheme);
        }

        // For the other requests, return null to let the base methods
        // decide what's the best scheme based on the default schemes
        // configured in the global authentication options.
        return null;
    }


}

I am not sure how to implement this "GetSchemeAsync".我不确定如何实现这个“GetSchemeAsync”。 I am also not sure what I am trying to achieve is the right way or not我也不确定我要达到的目标是否正确

Use the Authorize attribute on your controllers action where your need to authorize a user read the doc在您需要授权用户阅读文档的控制器操作上使用 Authorize 属性

If you it want to be more global, you can use an Authorization filter如果你想更全球化,你可以使用授权过滤器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM