DB-First authentication confusion with ASP.NET Web API 2 + EF6

后端 未结 2 1845
长情又很酷
长情又很酷 2020-12-05 03:26

I need to create a Web API C# application for an existing MySQL database. I\'ve managed to use Entity Framework 6 to bind every database table to a RESTful API (that all

2条回答
  •  再見小時候
    2020-12-05 04:06

    Since your DB schema are not compatible with default UserStore You must implement your own UserStore and UserPasswordStore classes then inject them to UserManager. Consider this simple example:

    First write your custom user class and implement IUser interface:

    class User:IUser
    {
        public int ID {get;set;}
        public string Username{get;set;}
        public string Password_hash {get;set;}
        // some other properties 
    }
    

    Now author your custom UserStore and IUserPasswordStore class like this:

    public class MyUserStore : IUserStore, IUserPasswordStore
    {
        private readonly MyDbContext _context;
    
        public MyUserStore(MyDbContext context)
        {
            _context=context;
        }
    
        public Task CreateAsync(AppUser user)
        {
            // implement your desired logic such as
            // _context.Users.Add(user);
        }
    
        public Task DeleteAsync(AppUser user)
        {
            // implement your desired logic
        }
    
        public Task FindByIdAsync(string userId)
        {
            // implement your desired logic
        }
    
        public Task FindByNameAsync(string userName)
        {
            // implement your desired logic
        }
    
        public Task UpdateAsync(AppUser user)
        {
            // implement your desired logic
        }
    
        public void Dispose()
        {
            // implement your desired logic
        }
    
        // Following 3 methods are needed for IUserPasswordStore
        public Task GetPasswordHashAsync(AppUser user)
        {
            // something like this:
            return Task.FromResult(user.Password_hash);
        }
    
        public Task HasPasswordAsync(AppUser user)
        {
            return Task.FromResult(user.Password_hash != null);
        }
    
        public Task SetPasswordHashAsync(AppUser user, string passwordHash)
        {
            user.Password_hash = passwordHash;
            return Task.FromResult(0);
        }
    }
    

    Now you have very own user store simply inject it to the user manager:

    public class ApplicationUserManager: UserManager
    {
        public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context)
        {
             var manager = new ApplicationUserManager(new MyUserStore(context.Get()));
             // rest of code
        }
    }
    

    Also please note you must directly inherit your DB Context class from DbContext not IdentityDbContext since you have implemented own user store.

提交回复
热议问题