casbin-net / casbin-aspnetcore

Casbin.NET integration middleware and sample code for ASP.NET Core
https://github.com/casbin/Casbin.NET
Apache License 2.0
64 stars 20 forks source link

How can I make CasbinAuthorize work with a specific request transformer #33

Closed thoraj closed 2 years ago

thoraj commented 2 years ago

I am trying to override the default request transformer for individual controller actions.

Like so:

[CasbinAuthorize(RequestTransformerType = typeof(VerjiCasbinRequestTransformer))]
public async Task<IActionResult> SetPrimaryContact(string customerId, string personId)
{
   ...

The middleware is not able to pick up the transformer, and fails with:

System.ArgumentException: Can find any specified type request transformer. (Parameter 'RequestTransformerType')
   at Casbin.AspNetCore.Authorization.DefaultEnforcerService.EnforceAsync(ICasbinAuthorizationContext context)
   at Casbin.AspNetCore.Authorization.Policy.CasbinAuthorizationHandler.HandleRequirementAsync(AuthorizationHandlerContext context, CasbinAuthorizationRequirement requirement, ICasbinAuthorizationContext casbinContext)
   at Microsoft.AspNetCore.Authorization.AuthorizationHandler`2.HandleAsync(AuthorizationHandlerContext context)
   at Microsoft.AspNetCore.Authorization.DefaultAuthorizationService.AuthorizeAsync(ClaimsPrincipal user, Object resource, IEnumerable`1 requirements)
   at Casbin.AspNetCore.Authorization.CasbinEvaluator.AuthorizeAsync(ICasbinAuthorizationContext casbinContext, AuthorizationPolicy policy, AuthenticateResult authenticationResult)
   at Casbin.AspNetCore.Authorization.CasbinAuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
   at AspNetCoreRateLimit.RateLimitMiddleware`1.Invoke(HttpContext context) in C:\Users\User\Documents\Github\AspNetCoreRateLimit\src\AspNetCoreRateLimit\Middleware\RateLimitMiddleware.cs:line 123
   at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)

Not sure how to make CasbinAuthorizeAttribute() use the specific transformer. I've tried creating the transformer in the same namespace as the controller, but with the same result.

casbin-bot commented 2 years ago

@Sagilio @xcaptain @huazhikui

sagilio commented 2 years ago

@thoraj You may need to add a service like this?

services.AddSingleton<IRequestTransformer, VerjiCasbinRequestTransformer>();
thoraj commented 2 years ago

Thanks.

Registering the type did the trick.