如何在现有数据库中使用新的MVC5身份验证 [英] How to use new MVC5 Authentication with existing database

查看:79
本文介绍了如何在现有数据库中使用新的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进行身份验证,然后我将可以通过User属性从任何控制器访问用户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.

推荐答案

假设您正在使用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));
    }

请注意,User属性将包含用户的声明,并且NameIdentifier声明将映射到Identity系统中的IUser.Id属性.这并不直接与只是用户名/秘密存储的IUserSecret绑定.系统将本地密码建模为providerKey =用户名和loginProvider ="Local"的本地登录名

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: IdentityAuthenticationmanager.GetUserClaims的实现中也存在一个错误,该错误会强制转换为User而不是IUser,因此从User扩展而来的自定义用户将无法正常工作.

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

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

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