Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 770
Big boy Avatar asked Oct 17 '25 19:10

Big boy


1 Answers

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
like image 88
CodingMytra Avatar answered Oct 19 '25 07:10

CodingMytra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!