简体   繁体   中英

Alternative to ActionFilterAttribute in ASP.net core

I am trying to authenticate users in my asp.net core 2.2 application. This is how we use to do it in asp.net web api using .net 4.5

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. 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 . 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". 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

If you it want to be more global, you can use an Authorization filter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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