10

I've looked through the current literature but I'm struggling to workout exactly how to make the new IdentityStore system work with your own database.

My database's User table is called tblMember an example class below.

public partial class tblMember
{
    public int id { get; set; }
    public string membership_id { get; set; }
    public string password { get; set; }
    ....other fields
}

currently users login with the membership_id which is unique and then I use the id throughout the system which is the primary key. I cannot use a username scenario for login as its not unique enough on this system.

With the examples I've seen it looks like the system is designed to me quite malleable, but i cannot currently workout how to get the local login to use my tblmember table to authenticate using membership_id and then I will have access the that users tblMember record from any of the controllers via the User property.

http://blogs.msdn.com/b/webdev/archive/2013/07/03/understanding-owin-forms-authentication-in-mvc-5.aspx

Eonasdan
  • 7,563
  • 8
  • 55
  • 82
Tim
  • 7,401
  • 13
  • 61
  • 102

1 Answers1

5

Assuming you are using EF, you should be able to do something like this:

public partial class tblMember : IUserSecret
{
    public int id { get; set; }
    public string membership_id { get; set; }
    public string password { get; set; }
    ....other fields

    /// <summary>
    /// Username
    /// </summary>
    string UserName { get { return membership_id; set { membership_id = value; }

    /// <summary>
    /// Opaque string to validate the user, i.e. password
    /// </summary>
    string Secret { get { return password; } set { password = value; } }
}

Basically the local password store is called the IUserSecretStore in the new system. You should be able to plug in your entity type into the AccountController constructor like so assuming you implemented everything correctly:

    public AccountController() 
    {
        var db = new IdentityDbContext<User, UserClaim, tblMember, UserLogin, Role, UserRole>();
        StoreManager = new IdentityStoreManager(new IdentityStoreContext(db));
    }

Note the User property will contain the user's claims, and the NameIdentifier claim will map to the IUser.Id property in the Identity system. That is not directly tied to the IUserSecret which is just a username/secret store. The system models a local password as a local login with providerKey = username, and loginProvider = "Local"

Edit: Adding an example of a Custom User as well

    public class CustomUser : User {
        public string CustomProperty { get; set; }
    }

    public class CustomUserContext : IdentityStoreContext {
        public CustomUserContext(DbContext db) : base(db) {
            Users = new UserStore<CustomUser>(db);
        }
    }

    [TestMethod]
    public async Task IdentityStoreManagerWithCustomUserTest() {
        var db = new IdentityDbContext<CustomUser, UserClaim, UserSecret, UserLogin, Role, UserRole>();
        var manager = new IdentityStoreManager(new CustomUserContext(db));
        var user = new CustomUser() { UserName = "Custom", CustomProperty = "Foo" };
        string pwd = "password";
        UnitTestHelper.IsSuccess(await manager.CreateLocalUserAsync(user, pwd));
        Assert.IsTrue(await manager.ValidateLocalLoginAsync(user.UserName, pwd));
        CustomUser fetch = await manager.Context.Users.FindAsync(user.Id) as CustomUser;
        Assert.IsNotNull(fetch);
        Assert.AreEqual("Custom", fetch.UserName);
        Assert.AreEqual("Foo", fetch.CustomProperty);
    }

EDIT #2: There's also a bug in the implementation of IdentityAuthenticationmanager.GetUserClaims that is casting to User instead of IUser, so custom users that are not extending from User will not work.

Here's the code that you can use to override:

    internal const string IdentityProviderClaimType = "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider";
    internal const string DefaultIdentityProviderClaimValue = "ASP.NET Identity";

/// <summary>
/// Return the claims for a user, which will contain the UserIdClaimType, UserNameClaimType, a claim representing each Role
/// and any claims specified in the UserClaims
/// </summary>
public override async Task<IList<Claim>> GetUserIdentityClaims(string userId, IEnumerable<Claim> claims) {
    List<Claim> newClaims = new List<Claim>();
    User user = await StoreManager.Context.Users.Find(userId) as IUser;
    if (user != null) {
        bool foundIdentityProviderClaim = false;
        if (claims != null) {
            // Strip out any existing name/nameid claims that may have already been set by external identities
            foreach (var c in claims) {
                if (!foundIdentityProviderClaim && c.Type == IdentityProviderClaimType) {
                    foundIdentityProviderClaim = true;
                }
                if (c.Type != ClaimTypes.Name &&
                    c.Type != ClaimTypes.NameIdentifier) {
                    newClaims.Add(c);
                }
            }
        }
        newClaims.Add(new Claim(UserIdClaimType, userId, ClaimValueTypes.String, ClaimsIssuer));
        newClaims.Add(new Claim(UserNameClaimType, user.UserName, ClaimValueTypes.String, ClaimsIssuer));
        if (!foundIdentityProviderClaim) {
            newClaims.Add(new Claim(IdentityProviderClaimType, DefaultIdentityProviderClaimValue, ClaimValueTypes.String, ClaimsIssuer));
        }
        var roles = await StoreManager.Context.Roles.GetRolesForUser(userId);
        foreach (string role in roles) {
            newClaims.Add(new Claim(RoleClaimType, role, ClaimValueTypes.String, ClaimsIssuer));
        }
        IEnumerable<IUserClaim> userClaims = await StoreManager.Context.UserClaims.GetUserClaims(userId);
        foreach (IUserClaim uc in userClaims) {
            newClaims.Add(new Claim(uc.ClaimType, uc.ClaimValue, ClaimValueTypes.String, ClaimsIssuer));
        }
    }
    return newClaims;
}
Rhapsody
  • 6,017
  • 2
  • 31
  • 49
Hao Kung
  • 28,040
  • 6
  • 84
  • 93
  • Could you please provide a complete example. I would like to user my own User class that maps to my Users table. Looks like there I'm not the only one looking for a solution: http://stackoverflow.com/questions/17399933/how-do-i-configure-the-users-context-table – Michael Olesen Jul 16 '13 at 14:27
  • Edited my answer to contain a custom User, you would likely implement IUser instead of extend User, but the rest of the code should be the same – Hao Kung Jul 16 '13 at 18:20
  • @Hao Kung, I'm currently confused as to how to implement this correctly, i appreciate that this is still in beta but there appears no real detail about customising and linking to your own database/password store, are there any more examples/resources which you are aware of? – Tim Jul 22 '13 at 06:24
  • @HaoKung - what if you're *not* using EF? I've plugged in a custom IIdentityContext implementation with all the stores and entities replaced with my owm implementations that work with NHibernate. Registering and logging in and so forth works - at least at the functional level - but something's then going wrong at the OWIN level and no claims are being passed to the page, so the anti forgery token trips up. I'm tearing my hair out. I know it's a beta but the dependency on EF is a real problem for us evaluating MVC5. – Neil Hewitt Jul 30 '13 at 16:51
  • So the AntiForgery stuff is actually at the claims layer, its expectation is that there is a NameIdentifier set, the issue is most likely with the GetUserClaims method. Make sure that your implementation is returning some kind of unique name identifier so AntiForgery is happy. – Hao Kung Jul 30 '13 at 18:31
  • 1
    Ah i see the issue, so in the Preview-Refresh bits, there was a bug in the implementation in GetUserClaims that tries to cast the user specifically to User, so you will have to override and reimplement this method to fix that. I'll edit my answer. – Hao Kung Jul 30 '13 at 18:36
  • @Hao Kung How would I go a head and do it if I want the the CustomUser to simply be named User? Whenever I try to implement the IUser i get the following error: A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' or 'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider' was not present on the provided ClaimsIdentity. To enable anti-forgery token support with claims-based authentication, please verify that the configured claims provider is providing both of these claims on the ClaimsIdentity instances it generates. If the configure – Martin Jul 16 '13 at 19:37
  • Perhaps this will help: http://brockallen.com/2012/07/08/mvc-4-antiforgerytoken-and-claims/. It describes the issue related to anti forgery and claims. – Brock Allen Sep 28 '13 at 01:40