skip to Main Content

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


  1. You can check the role in the method, something like this:

    [HttpGet("getAll"), Authorize]
            public async Task<IActionResult> GetAll()
            {
                if (!Roles.Any(r => r == "getAll"))
                {
                    return Unauthorized("Pass the role name");
                }
    
                return Ok();
            }
    

    Roles contains the roles that user access

    Login or Signup to reply.
  2. 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 of AuthorizeAttribute then use as attribute above actions/controllers without Attribute 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search