Reputation: 5596
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
Upvotes: 1
Views: 1275
Reputation: 17444
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
Upvotes: 1