How to check user is in many roles in asp.net iden

2019-01-28 21:14发布

问题:

Hi I need to check if a user is in one of the roles and i am confused with different versions of code that i found. Let me show you what i have at the moment first

_manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());

var currentUser = _manager.FindById(User.Identity.GetUserId());      

if (!_manager.IsInRole(currentUser.Id, "admin"))
{

}

And ApplicationUser

public class ApplicationUser : IdentityUser
{        
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{

}

So i want to check if the user is in one of the roles. e.g. admin, controbutor, superuser, etc.

I found this example which seems a good one but i have to put the following changes in web.config to make it work. I didn't need to do that with my code as i have currently.

roleManager enabled="true"

I try to research more on UserManager.IsInRole but I coundn't find many about it. A bit more reading i understand the post i found is about Simple Membership.

As I am using Identity, i should not use the code that i found (refers to the link and accepted answer) as that will be mixing of Identity and Simple Membership? Specially i refer to this line Roles.GetRolesForUser. Is there similar method for Identity? I think I am confused about different membership frameworks and don't know what is the proper uses. I hope someone can explain me to understand.

(I still want the solution for the question i asked in the title but i really need to understand as well =)

回答1:

Well I found a way to do it. I didn't know User object that returns by UserManager has Roles property with the collection of roles that the user has.

using Microsoft.AspNet.Identity;
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());

var roles = new List<string> { "admin", "contributor" };
var currentUser = manager.FindById(User.Identity.GetUserId());  

if (currentUser.Roles.Any(u => roles.Contains(u.Role.Name)))
{

}     

More information on Asp.net Identity membership .. this seems like good resource.

http://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples/



回答2:

Well I guess it all depends on what your requirements are i.e. use simple membership if you can. IF you integrate the membership correctly (Forms Authentication) then you should really use User.IsInRole("Role").

It looks like by what you have posted that you are using your own custom user objects so in this scenario i would use a custom membership provider there are lots of examples of this on the net here the first 1 i found http://www.codeproject.com/Articles/165159/Custom-Membership-Providers

The idea is to just override all the Membership methods and return your own user data from your service layer.

Hope that helps. Lee