I use the below the line for role based authentication at top of methods in controllers
[HttpGet("getAll"), Authorize(Roles = "GetAll")]
When a user doesn’t have access to this role, I want to tell the user that you need the role "GetAll"
Is it possible?
2
Answers
You can check the role in the method, something like this:
Roles contains the roles that user access
I know I am very late but it may help someone in future.
I have added an action filter and uses it on actions/controllers. I have added it to my template too, https://github.com/arham-anees/CleanArchitectureNetCore/blob/main/CleanArhitectureNetCore.WebApi/ActionFilters/Authorize.cs
First of all create an attribute class
public class AuthorizeAttribute:Attribute, IAuthorizationFilter
. You can name anything instead ofAuthorizeAttribute
then use as attribute above actions/controllers withoutAttribute
part.The action will be called anytime action is called and will perform action and perform your actions. For role based Authenticated, I have kept my controllers clean with attributes while authenticating user on basis of role. you can see it here https://github.com/arham-anees/CleanArchitectureNetCore/blob/main/CleanArhitectureNetCore.WebApi/Controllers/ValuesController.cs#L18