I am trying to port some old code over to .Net Core 3.
With the old AuthorizeAttibutes you could get an Action's verb from HttpActionContext through
var verb = actionContext.Request.Method.Method;
In Core 3.0, HttpActionContext has now changed to AuthorizationHandlerContext.
I have seen some posts mentioning mentioning to use:
var filterContext = context.Resource as AuthorizationFilterContext;
var httpMethod = filterContext.HttpContext.Request.Method;
but in .Net Core 3 I don't see AuthorizationFilterContext on context.Resource for a normal controller or api controller.
Any ideas / pointers as to how I can get the VERB used in the request for the action?
EDIT: So with the help of @xing-zou I was able to do the following POC to get to a unique route key that I can compare with my routes in the db and the roles assigned to them.
If the user belongs to a role that has been associated to a route, then the user will get access otherwise 403 Forbidden
public class AccessToRouteHandler : AuthorizationHandler<AccessToRouteRequirement>
{
private readonly IHttpContextAccessor httpContextAccessor;
private readonly DbContext dbContext;
public AccessToRouteHandler(IHttpContextAccessor httpContextAccessor, DbContext dbContext)
{
this.httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
this.dbContext = dbContext;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccessToRouteRequirement requirement)
{
var filterContext = context.Resource as AuthorizationFilterContext;
var routeInfo = context.Resource as RouteEndpoint;
var response = filterContext?.HttpContext.Response;
if (!context.User.Identity.IsAuthenticated || string.IsNullOrEmpty(context.User.Identity.Name))
{
response?.OnStarting(async () =>
{
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
});
context.Fail();
return Task.CompletedTask;
}
var verb = this.httpContextAccessor.HttpContext.Request.Method;
var routeKey = string.Empty;
if (context.Resource is Endpoint endpoint)
{
var cad = endpoint.Metadata.OfType<ControllerActionDescriptor>().FirstOrDefault();
var controllerFullName = cad.ControllerTypeInfo.FullName;
var actionName = cad.ActionName;
var bindings = cad.Parameters;
var actionParams = ".";
if (bindings.Any())
{
bindings.ToList().ForEach(p => actionParams += p.ParameterType.Name + ".");
}
routeKey = $"{controllerFullName}.{actionName}{actionParams}{verb}";
}
var route = dbContext.Routes
.Include(t => t.Roles)
.FirstOrDefault(r => r.RouteKey == routeKey);
if (route != null && route.Roles.Any(role => context.User.HasClaim(c => c.Value == role)))
{
// user belong to a role associated to the route.
context.Succeed(requirement);
return Task.CompletedTask;
}
response?.OnStarting(async () =>
{
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
});
context.Fail();
return Task.CompletedTask;
}
}
In asp.net core 3.0 with endpoint routing enabled, you could register IHttpContextAccessor
to get the current HttpContext, then you could get the http
method.
Take below Policy-based authorization as an example:
public class AccountRequirement : IAuthorizationRequirement { }
public class AccountHandler : AuthorizationHandler<AccountRequirement>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public AccountHandler(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
AccountRequirement requirement)
{
var httpMethod = _httpContextAccessor.HttpContext.Request.Method;
if (httpMethod == "POST")
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
In Startup:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddControllersWithViews();
services.AddRazorPages();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthorization(options =>
{
options.AddPolicy("Account",
policy => policy.Requirements.Add(new AccountRequirement()));
});
services.AddSingleton<IAuthorizationHandler, AccountHandler>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With