2016-05-25 90 views
0

我正在學習MVC和創建登錄並註冊自定義現有數據庫我跟隨this tutorial並創建自定義用戶管理器和登錄管理器。它允許我正確地註冊用戶,並且用戶可以正確保存在我的數據庫中。但是密碼被保存爲沒有加密的字符串,因爲用戶已輸入密碼並且登錄時CheckPasswordAsync返回System.FormatException:Base-64字符數組或字符串的無效長度。爲了實現UserPasswordStore我跟着我的自定義signinmanager this tutorial 代碼和用戶存儲是Base-64字符數組或字符串的無效長度。在UserManager.CheckPasswordAsync(用戶,密碼)

public class CustomUserManager : UserManager<MyAppUser> 
{ 
    public CustomUserManager(IUserStore<MyAppUser> store) : base(store) { } 

    internal static CustomUserManager Create() 
    { 
     return new CustomUserManager(new CustomUserStore()); 
    } 

    public override Task<bool> CheckPasswordAsync(MyAppUser user, string password) 
    { 
     return base.CheckPasswordAsync(user, password); 
    } 
} 

public class CustomUserStore : IUserStore<MyAppUser>, IUserPasswordStore<MyAppUser> 
{ 
    private LearningDBContext database; 

    public Task CreateAsync(MyAppUser user) 
    { 
     try 
     { 
      var context = userStore.Context as LearningDBContext; 
      context.MyAppUsers.Add(user); 
      context.Configuration.ValidateOnSaveEnabled = false; 
      return context.SaveChangesAsync(); 
     } 
     catch { } 
     return Task.FromResult<bool>(true); 
    } 

    #endregion 


    #region Password Store Region 
    public Task SetPasswordHashAsync(MyAppUser user, string passwordHash) 
    { 
     var identityUser = ToIdentityUser(user); 
     var task = userStore.HasPasswordAsync(identityUser); 
     setMyAppUser(user, identityUser); 
     return Task.FromResult(0); 
    } 

    private void setMyAppUser(MyAppUser user, IdentityUser identityUser) 
    { 
     user.Password = identityUser.PasswordHash; 
     user.Id = identityUser.Id; 
     user.UserName = identityUser.UserName; 
    } 

    public Task<string> GetPasswordHashAsync(MyAppUser user) 
    { 
     var identityUser = ToIdentityUser(user); 
     var task = userStore.GetPasswordHashAsync(identityUser); 
     setMyAppUser(user, identityUser); 
     return task; 
    } 

    public Task<bool> HasPasswordAsync(MyAppUser user) 
    { 
     var identityUser = ToIdentityUser(user); 
     var task = userStore.HasPasswordAsync(identityUser); 
     setMyAppUser(user, identityUser); 
     return task; 
    } 

    private IdentityUser ToIdentityUser(MyAppUser user) 
    { 
     return new IdentityUser() 
     { 
      Id = user.Id, 
      PasswordHash = user.Password, 
      UserName = user.UserName 
     }; 
    } 
    #endregion 
} 

和控制器我打電話

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

我想不通的原因。任何人都可以幫忙嗎?

+0

你介意將代碼降低到重現問題所需的最小值嗎? –

+0

我編輯了代碼,以便只剩下所需的零件。但是,實現它的其餘功能將由Visual Studio自動生成。 – Rohit

+0

@Rohit這個「密碼保存爲沒有加密的字符串」讓我很擔心。你爲什麼這麼做?當密碼輸入器希望以Base64格式存儲爲密碼的密碼時,會出現此錯誤,但是您將爲其輸入純文本而不是Base64字符串。 – trailmax

回答

0

感謝@trailmax的幫助,我解決了這個問題。我直接保存密碼,因爲我在使用默認實現時沒有覆蓋系統正在檢查散列密碼。所以,我需要保存散列密碼或重寫CheckPassword方法來手動檢查。它適用於兩種方式。

相關問題