Home > Software engineering >  Role base authentication with custom error with role name in dot net 6
Role base authentication with custom error with role name in dot net 6

Time:01-06

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?

CodePudding user response:

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

  •  Tags:  
  • Related