Question

would appreciate help on this subject:

I'm trying to use my own roles, like I did on MVC4 (custom membership) I.E. [Authorize(roles="Admin")] for some controllers. I'm a bit confused with the new Identity thing.

Later, I will also need to use the same roles for API controllers.

Can someone explain how in the simplest way I can achieve the following thing:

  1. Read from my SQL DB (entity) a "Login" class, which has Username, Password and a Role. (Role is an Enum of roles, {Admin = 1, Manager = 2...}
  2. Use the role from my Login, and translate it to use with the new "Identity".
  3. Manage regular controllers with [Authorize(roles="Admin")], [AllowAnonymous], etc
  4. Manage API controllers with same thing.

I've read the stuff about customizing, but it seems too complicated.

Anyone has a simple example of how to use it plain and simple?

Thanks

Was it helpful?

Solution

I do something like this:

 // Just for Reference
public interface IUserIdentity
{
    Guid UserId { get; set; }
    string UserName { get; set; }

}

Pass in a List which would contain your roles..

List<Claim> claims = new List<Claim>();

claims.Add(new Claim(ClaimType.Role,"Admin"));

 public ClaimsIdentity CreateIdentity(IUserIdentity user, IEnumerable<Claim> claims, string authenticationType)
    {
        var identity = new ClaimsIdentity(claims, authenticationType);
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString()));
        identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
        return identity;
    }

If you are using ASP.NET Identiy this can be done easily. The "out of the box" membership stuff still sucks.

OTHER TIPS

If you already have your own identity system in place, what's the reason for using ASP.NET Identity? Do you need Claims-support?

ASP.NET Identity can do all the things you described, but it is hard to integrate it into an existing membership system (because ASP.NET Identity was developed as a replacement of existing membership frameworks on the ASP.NET platform). Does your role system something special, f.e. are there any business rules integrated? If not, it shouldn't be hard to translate your role system to the role system ASP.NET Identity provides.

I will try to answer your points from an ASP.NET Identity point of view:

  1. This is handled by the IdentityUser class. There you'll find a Roles, UserName, and PasswordHash property. If you like to customize it you can add new properties in a derived class. Keep in mind that the Roles property is a collection of IdentityUserRoles, that means there is no enumeration built-in (it instead points to the IdentityRole class).
  2. Not necessary (see point 1).
  3. Can be used from ASP.NET Identity. Works the same way as before.
  4. Works the same way as before.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top