I am using .NET core 3 and for AuthorizationFilter inherited IAuthorizationFilter. On my top level attribute I have added custom attribute(ModulePermission).
I need to get the value of the attribute on AuthorizeActionFilter -> OnAuthorization function.
However, I can access current action customattribute(ActionPermission). But my top level attribute is null. ( var module = actionDescriptor.MethodInfo.GetCustomAttributes(true).FirstOrDefault(i => i is ModulePermissionAttribute); )
Example
Api Controller:
[ModulePermission(Module.Product)]
[Route("api/products")]
[ApiController]
public class ProductController : BaseApiController
{
public ProductController()
{
}
[Route(""), HttpPost, ActionPermission(Action.READ)]
public Response<Product> Get()
{
// some code
}
}
Authorization Class:
using System;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
public enum Module
{
User,
Product
}
public enum Action
{
Read,
Delete,
Add,
Edit
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ActionPermissionAttribute : Attribute
{
private Action _action;
public Action action { get { return action; } }
public ActionPermissionAttribute(Action action = Action.Read)
{
_action = action;
}
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ModulePermissionAttribute : Attribute
{
private string _module;
public string Module { get { return _module; } }
public ModulePermissionAttribute(string module = "")
{
if (string.IsNullOrEmpty(module))
{
_module = "Novalue";
}
else
{
_module = module;
}
}
public ModulePermissionAttribute(Type module)
{
_module = module.Name;
}
}
public class AuthorizeAttribute : TypeFilterAttribute
{
public AuthorizeAttribute()
: base(typeof(AuthorizeActionFilter))
{
}
}
public class AuthorizeActionFilter : IAuthorizationFilter
{
public AuthorizeActionFilter()
{
}
public void OnAuthorization(AuthorizationFilterContext context)
{
bool isAuthorized = //check authorized or not
var actionDescriptor = (context.ActionDescriptor as ControllerActionDescriptor);
var module = actionDescriptor.MethodInfo.GetCustomAttributes<ModulePermissionAttribute>(true).FirstOrDefault(i => i is ModulePermissionAttribute);
// **here module is always null**
var method = actionDescriptor.MethodInfo.GetCustomAttributes<ActionPermissionAttribute>(false).FirstOrDefault(i => i is ActionPermissionAttribute);
// check module and method exists for the user
if (!isAuthorized)
{
context.Result = new ForbidResult();
}
}
}
CodePudding user response:
Found the answer By Using EndpointMetadata
var module = context.ActionDescriptor.EndpointMetadata.OfType<ModulePermissionAttribute>().FirstOrDefault();
Hope this helps someone