Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net identity get all roles of logged in user

I created a role based menu for which I followed this tutorial. Some where down that page you'll see this line of code:

String[] roles = Roles.GetRolesForUser(); 

It returns all roles of the currently logged in user. I was wondering how to accomplish this with the new ASP.NET Identity system?

It's still pretty new and there is not much to find about it.

like image 594
Quoter Avatar asked Feb 10 '14 22:02

Quoter


People also ask

How to get user roles in c#?

You can use Roles. GetRolesForUser() method to get all the rols user belong to . use it like this; string[] rolesuserbelongto = Roles.

Which method enables you to return a list of users in a role that has a particular UserName?

The following code example uses the GetUsersInRole method to get a list of the users in a particular role and binds the results to a GridView control.


1 Answers

Controller.User.Identity is a ClaimsIdentity. You can get a list of roles by inspecting the claims...

var roles = ((ClaimsIdentity)User.Identity).Claims                 .Where(c => c.Type == ClaimTypes.Role)                 .Select(c => c.Value); 

--- update ---

Breaking it down a bit more...

using System.Security.Claims;  // ........  var userIdentity = (ClaimsIdentity)User.Identity; var claims = userIdentity.Claims; var roleClaimType = userIdentity.RoleClaimType; var roles = claims.Where(c => c.Type == ClaimTypes.Role).ToList();  // or... var roles = claims.Where(c => c.Type == roleClaimType).ToList(); 
like image 195
Anthony Chu Avatar answered Oct 03 '22 03:10

Anthony Chu