Home > Software design >  How to check that user is in a role programmatically in ASP.NET Core?
How to check that user is in a role programmatically in ASP.NET Core?

Time:07-06

I know about attribute-based authorization.

I know that we can add [Authorize (Role = 'RoleName')] to limit access for an action or a controller to that person only.

However, in this particular case, I need to programmatically check that user is in role, INSIDE action.

[HttpGet]
public IActionResult DomSomething()
{
    // How can I know that user has a role here?
    return Ok();
}

How can I do that?

Update

I'm not using ASP.NET Core Identity.

I'm using KeyCloak (OAuth provider).

CodePudding user response:

You can check it with userManager.IsInRoleAsync(user, role.Name). Inject userManager on your controller. And use like below:

[HttpGet]
public IActionResult DomSomething()
{
   if(userManager.IsInRoleAsync(user, role.Name)){
     // Do your stuff
   }
    return Ok();
}

CodePudding user response:

with the assumptions that your API is using authorize attribute, you can following inside the action.

HttpContext.User.IsInRole("role you want");

if this doesn't work then next you can try check in the claims list for role.

HttpContext.User.Claims

CodePudding user response:

UserId and RoleName are stored in the Role table

In the following method, we check if the name of the given role in Table Role is for the desired person, it will send true :

private bool UserCheckInRole(int userId , string roleName)
{
   if(RoleTable.Where(role => role.roleName == roleName , role.UserId ==   
       userId).Any()) return true;
  return false;
}

[HttpGet]
public IActionResult DomSomething(string roleName = "")
{
    if(UserCheckInRole(userId , roleName){
        //true
    }
    // How can I know that user has a role here?
    return Ok();
}
  • Related