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

查看:21
本文介绍了如何在现有数据库中使用新的 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.

我的数据库的 User 表被称为 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.

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

注意 User 属性将包含用户的声明,NameIdentifier 声明将映射到身份系统中的 IUser.Id 属性.这与 IUserSecret 没有直接关联,它只是一个用户名/秘密存储.系统将本地密码建模为本地登录名,providerKey = username,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"

添加自定义用户的示例

    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天全站免登陆