Microsoft. AspNet. Identity: use the existing table-Logon implementation, aspnet. identity

Source: Internet
Author: User

Microsoft. AspNet. Identity: use the existing table-Logon implementation, aspnet. identity

Microsoft. AspNet. Identity is a new membership framework introduced by Microsoft. It is also an implementation of the Microsoft Owin standard. Microsoft. AspNet. Identity. EntityFramework is the data Implementation of Microsoft. AspNet. Identity. However, there are some problems when using this framework. For a brand new project, you can also use the default table name and field name provided by it. However, it is troublesome to apply this framework on some old databases. Therefore, we implement a Microsoft. AspNet. Identity. EntityFramework

First, we only talk about logon. the login entry code is

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

The code in the corresponding Owin framework is

public virtual async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout){    SignInStatus result;    if (this.UserManager == null)    {        result = SignInStatus.Failure;    }    else    {        TUser tUser = await this.UserManager.FindByNameAsync(userName).WithCurrentCulture<TUser>();        if (tUser == null)        {            result = SignInStatus.Failure;        }        else if (await this.UserManager.IsLockedOutAsync(tUser.Id).WithCurrentCulture<bool>())        {            result = SignInStatus.LockedOut;        }        else if (await this.UserManager.CheckPasswordAsync(tUser, password).WithCurrentCulture<bool>())        {            await this.UserManager.ResetAccessFailedCountAsync(tUser.Id).WithCurrentCulture<IdentityResult>();            result = await this.SignInOrTwoFactor(tUser, isPersistent).WithCurrentCulture<SignInStatus>();        }        else        {            if (shouldLockout)            {                await this.UserManager.AccessFailedAsync(tUser.Id).WithCurrentCulture<IdentityResult>();                if (await this.UserManager.IsLockedOutAsync(tUser.Id).WithCurrentCulture<bool>())                {                    result = SignInStatus.LockedOut;                    return result;                }            }            result = SignInStatus.Failure;        }    }    return result;}

From this code, we can probably know that the login process is, of course, the login failure process will not be implemented first. The implementation is also very simple, just implement the corresponding interface according to the source code of Owin.

1. FindByNameAsync first finds the user object based on the login name, and uses UserStroe in UserManager to implement the IUserStore Interface Method

2. IsLockedOutAsync: Check whether the logon is locked. Use the IUserLockoutStore interface method implemented by UserStroe in UserManager.

3. CheckPasswordAsync: Check the password. Use the IUserPasswordStore interface implemented by UserStroe in UserManager.

4. ResetAccessFailedCountAsync: log on successfully, reset the logon Failure count, and use the IUserLockoutStore interface method implemented by UserStroe in UserManager.

5. SignInOrTwoFactor dual authentication, using the IUserTwoFactorStore interface method implemented by UserStroe in UserManager

 

SignInManager is the entry and UserManager is required. UserManager needs to use key UserStore. For more information about the framework, see other articles in the garden, and clearly explains why such a design is needed.

Implementation

There are existing resources. If we already have a database, a user table, the guid type of the id field, and a loginid, the username in the source code.

The first step is to implement our own SignInManager, inherited from Microsoft. AspNet. Identity. Owin. SignInManager <TUser, TKey>

public class WXSignInManager : SignInManager<WXUser, Guid>    {        public WXSignInManager(UserManager<WXUser, Guid> userManager, IAuthenticationManager authenticationManager) : base(userManager, authenticationManager)        {        }        public static WXSignInManager Create(IdentityFactoryOptions<WXSignInManager> options, IOwinContext context)        {            return new WXSignInManager(context.GetUserManager<WXUserManager>(), context.Authentication);        }

In our SignInManager code, there is a line of context. GetUserManager <WXUserManager> (), so we continue to implement our UserManager.

Step 2: implement our own UserManager, inherited from Microsoft. AspNet. Identity. UserManager <TUser, TKey>

public class WXUserManager : UserManager<WXUser, Guid>    {        public WXUserManager(IUserStore<WXUser, Guid> store) : base(store)        {        }        public static WXUserManager Create(IdentityFactoryOptions<WXUserManager> options, IOwinContext context)        {            return new WXUserManager(new WXUserStore(context.Get<WXDBContexnt>()))            {                PasswordHasher = new MyPasswordHasher()            };        }    }

From the previous Owin source code, we can know that all the key code is in UserStore. Next

Step 3: implement our own UserStore and implement the interfaces respectively.

Microsoft. AspNet. Identity. IUserStore <TUser, in TKey>, // database access interface

Microsoft. AspNet. Identity. IUserLockoutStore <TUser, in TKey>, // user lock, Logon Failure count Interface

Microsoft. AspNet. Identity. IUserPasswordStore <TUser, in TKey>, // User Password Interface

Microsoft. AspNet. Identity, IUserTwoFactorStore <TUser, in TKey> // interface for dual Authentication

public class WXUserStore : IUserStore<WXUser, Guid>, IUserLockoutStore<WXUser, Guid>, IUserPasswordStore<WXUser, Guid>, IUserTwoFactorStore<WXUser, Guid>        {            public WXUserStore(WXDBContexnt dbContext)            {                this.dbContext = dbContext;            }            WXDBContexnt dbContext;            public async Task<WXUser> FindByIdAsync(Guid userId)            {                var user = await dbContext.WXUser.FindAsync(userId);                return user;            }            public async Task<WXUser> FindByNameAsync(string userName)            {                return dbContext.WXUser.Where(p => p.LoginId == userName).FirstOrDefaultAsync();            }            public Task ResetAccessFailedCountAsync(WXUser user)            {                return Task.FromResult(false);            }            public Task<bool> GetLockoutEnabledAsync(WXUser user)            {                return Task.FromResult(false);            }            public Task<string> GetPasswordHashAsync(WXUser user)            {                return Task.FromResult(user.LoginPWD);            }            public Task<bool> GetTwoFactorEnabledAsync(WXUser user)            {                return Task.FromResult(false);            }        }

Here is just a super simple login function, so unrelated implementations are deleted. Note that p => p. loginId = userName. The Login Name field in the original database is loginId. You can view the document for the meaning of the interface. I believe that the specific meaning can be guessed from the method name. The interface designed by others is good. <! _!>.

I use EF as the data source here. Of course, you can also use your own. You only need to replace the implementation in the FindByIdAsync and FindByNameAsync methods, even in these aspects, it is no problem to directly query data using ado.net. Wxuser I inherited the existing user object of the system, and then implemented the IUser interface with a strong type, because my original system object already has the username attribute. The wxuser. username attribute exists as the account used for user logon. So I implement the strong type.

Public class WXUser: an existing user entity object in the system. IUser <Guid> {Guid IUser <Guid>. id {get {return this. id ;}} string IUser <Guid>. userName {get {return this. loginId;} set {this. loginId = value ;}} public class WXDBContexnt: DbContext {public WXDBContexnt () {} public static WXDBContexnt Create () {return new WXDBContexnt ();} public DbSet <WXUser> WXUser {get; set ;}}

The general code is like this. Of course, there are still many methods to implement our own UserStore object, but I just need a login, right? It can be transformed slowly <! _!>

At the end of the writing, it can be estimated by rewriting. This is the default code generated by the new project. Why cannot I add [Table ("Users")]? [Column ("LoginId")], override to achieve the effect.

[Table ("Users")] public class ApplicationUser: IdentityUser {public async Task <ClaimsIdentity> GenerateUserIdentityAsync (UserManager <ApplicationUser> manager) {// note that authenticationType must be consistent with CookieAuthenticationOptions. the corresponding item defined in AuthenticationType matches var userIdentity = await manager. createIdentityAsync (this, DefaultAuthenticationTypes. applicationCookie); // Add the Custom User declaration return userIdentity here;} [Column ("LoginId")] public override string UserName {get {return base. userName;} set {base. userName = value ;}}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.