HOWTO使用与现有数据库的新MVC5认证 [英] Howto use new MVC5 Authentication with existing database

查看:275
本文介绍了HOWTO使用与现有数据库的新MVC5认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过目前的文献看,但我努力锻炼究竟如何使自己的数据库新的 IdentityStore 系统正常工作。

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.

我的数据库的用户表称为 tblMember 下面的示例类。

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
}

目前用户登录与 membership_id 这是独一无二的,然后我用整个系统,这是主键ID。我不能用一个用户名的情况进行登录其没有在此系统上没有足够的唯一的。

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.

使用我见过它看起来像系统设计对我来说相当有延展性,但我目前不能锻炼如何让本地登录使用的例子我 tblmember 表使用验证 membership_id ,然后我将有机会获得的,从任何通过用户属性控制器的用户tblMember纪录。

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.

<一个href=\"http://blogs.msdn.com/b/webdev/archive/2013/07/03/understanding-owin-forms-authentication-in-mvc-5.aspx\">http://blogs.msdn.com/b/webdev/archive/2013/07/03/understanding-owin-forms-authentication-in-mvc-5.aspx

推荐答案

假设你使用的是EF,你应该能够做这样的事:

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; } }
}

基本上,本地密码存储在新的系统,称为IUserSecretStore。你应该能够在你的实体类型插入的AccountController构造像这样假设你正确实施的一切:

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));
    }

请注意用户属性将包含用户的索赔,而索赔的NameIdentifier将映射到识别系统的IUser.Id财产。不直接依赖于这仅仅是一个用户名/秘密商店IUserSecret。该系统模型的本地密码作为本地登录与providerKey =用户名和loginProvider =本地

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"

编辑:添加自定义用户的例子,以及

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);
    }

编辑#2:还有在被转换为用户而不是IUSER不是从用户扩展将无法工作IdentityAuthenticationmanager.GetUserClaims,因此定制用户执行一个bug。

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.

这里的code,你可以用它来重写:

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;
}

这篇关于HOWTO使用与现有数据库的新MVC5认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆