Working with Identity Users and Roles – Accessing Roles After User Login

There is an issue in the Identity framework when the business requirements need a developer to interact with the roles that a user is assigned to as soon as the user object is created upon successful login. The Identity framework has a bug that has been posted online numerous times but is hard to identify through all of the other code that users post. Luckily there is a very easy fix for it.

The fix requires the use of the ApplicationUserManager so inside of the HttpPost Login ActionResult in the AccountController we need to instanciate a new userManager.

var userManager = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

We can then use this object to find the user in the AspNetUsers database table based off the email address that was passed in as part of the model.

var user = userManager.FindByEmail(model.Email);

At this point we can work with the user and roles such as checking to see if they are in a role:

userManager.IsInRole(user.Id, "Admin");

Or if this is being implemented in the register method we could automatically add them to a role or roles by passing in a string array of roles:

string[] roles = new string[] { "Admin", "Manager", "HeadCheese" };</pre>
userManager.AddToRoles(user.Id, roles);

Not overly complicated as long as you know that you can’t use the User.IsInRole functionality immediately after being logged in to deal with roles and know the little work around!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s