Get all roles of a logged in user in ASP.NET Identity

Introduction


In order to get all roles of a logged in user in ASP.NET Identity, use the GetRoles method of the ApplicationUserManager.

GetRoles Usage


// get the user manager from the owin context
ApplicationUserManager userManager = HttpContext.GetOwinContext().GetUserManager();

string userId = User.Identity.GetUserId();

// get user roles
List<string> roles = userManager.GetRoles(userId).ToList();

In preceding code, we get the application user manager by using the OWIN middleware. After that, we get the id of the current logged in user by using the GetUserId method and we pass it as a parameter to the GetRoles method. The GetRoles method will thus return a list of strings representing all roles of the logged in user.

Namespaces


To work with the different objects and methods used in this tutorial, you have to include the following namespaces:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;