如何在asp.net web api 2中自定义对我自己的表集的身份验证?

时间:2013-12-11 20:36:26

标签: asp.net-web-api asp.net-identity

在创建的默认AccountController中,我看到了

    public AccountController()
        : this(Startup.UserManagerFactory(), Startup.OAuthOptions.AccessTokenFormat)
    {
    }

在Startup.Auth.cs中,我看到了

    UserManagerFactory = () => 
                new UserManager<IdentityUser>(new UserStore<IdentityUser>());   

似乎 UserStore 的实施来自 Microsoft.AspNet.Identity.EntityFramework

因此,要自定义身份验证,我必须实现自己的UserStore版本,如

 class MYSTUFFUserStore<IdentityUser> : UserStore<IdentityUser>
 {
 } 

并覆盖方法,然后在Startup.Auth.cs

中执行此操作
UserManagerFactory = () => 
               new UserManager<IdentityUser>(new MYSTUFFUserStore<IdentityUser>());   

我正在寻找一种自定义身份验证的正确方法。

1 个答案:

答案 0 :(得分:44)

假设您的表名为AppUser,请将您自己的AppUser域对象转换为IUser(using Microsoft.AspNet.Identity),如下所示

using Microsoft.AspNet.Identity;
public class AppUser : IUser
{
    //Existing database fields
    public long AppUserId { get; set; }
    public string AppUserName { get; set; }
    public string AppPassword { get; set; }

    public AppUser()
    {
        this.Id = Guid.NewGuid().ToString();  
    }

    [Ignore]
    public virtual string Id { get; set; }         
    [Ignore]
    public string UserName
    {
        get
        {
            return AppUserName;
        }
        set
        {
            AppUserName = value;
        }
    }
}

像这样实现UserStore对象

using Microsoft.AspNet.Identity;
public class UserStoreService 
         : IUserStore<AppUser>, IUserPasswordStore<AppUser>
{
    CompanyDbContext context = new CompanyDbContext();

    public Task CreateAsync(AppUser user)
    {            
        throw new NotImplementedException();
    }

    public Task DeleteAsync(AppUser user)
    {
        throw new NotImplementedException();
    }

    public Task<AppUser> FindByIdAsync(string userId)
    {
        throw new NotImplementedException();
    }

    public Task<AppUser> FindByNameAsync(string userName)
    {
        Task<AppUser> task = context.AppUsers.Where(
                              apu => apu.AppUserName == userName)
                              .FirstOrDefaultAsync();

        return task;
    }

    public Task UpdateAsync(AppUser user)
    {
        throw new NotImplementedException();
    }

    public void Dispose()
    {
        context.Dispose();
    }

    public Task<string> GetPasswordHashAsync(AppUser user)
    {
        if (user == null)
        {
            throw new ArgumentNullException("user");
        }

        return Task.FromResult(user.AppPassword);
    }

    public Task<bool> HasPasswordAsync(AppUser user)
    {
        return Task.FromResult(user.AppPassword != null);
    }

    public Task SetPasswordHashAsync(AppUser user, string passwordHash)
    {
        throw new NotImplementedException();
    }

}

如果您有自己的自定义密码哈希,则还需要实施IPasswordHasher。下面是一个没有密码散列的例子(哦不!)

using Microsoft.AspNet.Identity;
public class MyPasswordHasher : IPasswordHasher
{
    public string HashPassword(string password)
    {
        return password;
    }

    public PasswordVerificationResult VerifyHashedPassword
                  (string hashedPassword, string providedPassword)
    {
        if (hashedPassword == HashPassword(providedPassword))
            return PasswordVerificationResult.Success;
        else
            return PasswordVerificationResult.Failed;
    }
}

在Startup.Auth.cs中替换

UserManagerFactory = () => 
     new UserManager<IdentityUser>(new UserStore<IdentityUser>());

    UserManagerFactory = () => 
     new UserManager<AppUser>(new UserStoreService()) { PasswordHasher = new MyPasswordHasher() };

ApplicationOAuthProvider.cs中,将IdentityUser替换为AppUser

AccountController.cs中,将IdentityUser替换为AppUser,并删除所有外部身份验证方法,例如GetManageInfoRegisterExternal等。