"The input is not a valid Base-64 string" 从成员身份迁移到身份 2.0 后登录出现异常

"The input is not a valid Base-64 string" exception on login after migrating from membership to identity 2.0

我刚刚根据找到的说明 here 将我的网站从 memberhip 升级到 asp.net identity 2.0。我创建了新的注册和登录表单,并将我的用户数据迁移到新的数据库表中。

如果我使用 register.aspx 表单创建新用户,一切正常。新用户已保存到数据库中,我可以使用凭据登录。

但是,如果我尝试使用已迁移的现有用户登录,我会得到以下信息 System.FormatException:输入不是有效的 Base-64 字符串,因为它包含非-base 64字符,多于两个填充字符,或填充字符中有非法字符。

来自 Login.aspx.cs

protected void SignIn(object sender, EventArgs e)
    {
        var userStore = new UserStore<User>(new ApplicationDBContext());
        var userManager = new UserManager<User>(userStore);
        var user = userManager.Find(UserName.Text, Password.Text);

        if (user != null)
        {
            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
            var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

            authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);
            Response.Redirect("~/Default.aspx");
        }
        else
        {
            StatusText.Text = "Invalid username or password.";
            LoginStatus.Visible = true;
        }
    }

异常发生在这一行:

var user = userManager.Find(UserName.Text, Password.Text);

我设置了一个断点,看看它在轰炸什么,但它刚到代码中的那一行就停止了。

我认为这可能是由于我迁移密码的方式所致,因为新用户可以使用,但我没有看到任何与现有用户的 PasswordHash 列中的错误匹配的内容。

这是我在迁移用户时插入到 PasswordHash 列中的内容:

(aspnet_Membership.Password+'|'+CAST(aspnet_Membership.PasswordFormat as varchar)+'|'+aspnet_Membership.PasswordSalt)

我整个星期都在做这件事,如果有任何帮助,我们将不胜感激。

克里斯

在 Login.aspx.cs 文件中,我更改了

var userManager = new UserManager<User>(userStore);

var userManager = new UserManager();

这让我可以使用我的 UserManager 而不是身份来登录现有用户和新用户。

感谢 trailmax 为我指明了正确的方向!

您的问题是您的 UserManager 没有使用您从文章 SQLPasswordHasher 中获得的特殊密码散列。

UserManager 中的所有构造函数都应具有 this.PasswordHasher = new SQLPasswordHasher();

所以你的 UserManager 应该是:

public UserManager()
        : base(new UserStore<User>(new ApplicationDbContext()))
{
    this.PasswordHasher = new SQLPasswordHasher();
}

public UserManager(IUserStore userStore) : base(userStore)
{
    this.PasswordHasher = new SQLPasswordHasher();
}

如果不使用 SQLPasswordHasher,您将默认使用身份随附的标准 PasswordHasher,并且不适用于您的旧迁移密码 - 这就是您收到的错误消息。