简体   繁体   中英

How to check that user is in a role programmatically in ASP.NET Core?

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).

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();
}

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

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM