ASP.NET Identity中手动验证密码重置令牌

8

我想要手动验证ASP.NET身份2.0中的密码重置令牌。我试图创建我的版本UserManager.ResetPasswordAsync(string userId, string token, string newPassword),它接受IdentityUser而不是userId,像这样:

UserManager.ResetPasswordAsync(IdentityUser user, string token, string newPassword)

我不确定我的做法是否正确,但我在尝试验证之前通过电子邮件发送给用户的代码。我没有修改发送电子邮件和生成代码/令牌的代码。我认为调用这个方法是正确的,但是目的参数是不正确的。(我尝试了传递"ASP.NET身份",但无济于事。)

if (await userManager.UserTokenProvider.ValidateAsync(purpose: "?", token: code, manager: userManager, user: user))
{
    return IdentityResult.Success;
}
else
{
    return new IdentityResult("Invalid code.");
}

如果有人能向我解释一下它如何开箱即用,或者指向微软的源代码 UserManager.ResetPasswordAsync(IdentityUser user, string token, string newPassword),那就非常感激!
2个回答

9
我通过将目的设置为“ResetPassword”来克服了我的问题。
下面是最终结果的片段,以防有人想要做类似的事情。这是我ApplicationUserManager类中的一个方法。请注意,由于Microsoft代码中使用的某些私有变量、方法和资源无法访问,因此缺少一些异常处理或本地化。很遗憾他们没有把那些东西保护起来,这样我就可以得到它。对我来说,特别有趣(和奇怪)的是缺少的ThrowIfDisposed方法调用。显然,他们预期在实例被处理后进行方法调用,以提供更友好的错误消息并避免意外情况。
public async Task<IdentityResult> ResetPasswordAsync(IdentityUser user,
    string token, string newPassword)
{
    if (user == null)
    {
        throw new ArgumentNullException("user");
    }

    // Make sure the token is valid and the stamp matches.
    if (!await UserTokenProvider.ValidateAsync("ResetPassword", token, 
        this, user))
    {
        return IdentityResult.Failed("Invalid token.");
    }

    // Make sure the new password is valid.
    var result = await PasswordValidator.ValidateAsync(newPassword)
        .ConfigureAwait(false);
    if (!result.Succeeded)
    {
        return result;
    }

    // Update the password hash and invalidate the current security stamp.
    user.PasswordHash = PasswordHasher.HashPassword(newPassword);
    user.SecurityStamp = Guid.NewGuid().ToString();

    // Save the user and return the outcome.
    return await UpdateAsync(user).ConfigureAwait(false);
}

在我看来,它应该调用SetSecurityStampAsyncSetPasswordHashAsync而不是完整的UpdateAsync...这不是ASP.NET Identity混乱中他们做的第一件愚蠢的事情... - Vincent

3
根据位于以下位置的 Codeplex 存储库,Microsoft.AspNet.Identity 的代码似乎尚未开源:https://aspnetidentity.codeplex.com/SourceControl/latest#Readme.markdown。目前,ASP.NET Identity 框架代码不是公开的,因此将不会在此网站上发布。但是,我们计划改变这种情况,并且一旦我们能够做到,代码将在此存储库中发布。然而,我找到了这个调试符号基础上的 UserManager 源代码,可能是其源代码:UserManager Source Code。我还发现了以下帖子,这些帖子可能有所帮助:使用 ASP.NET Identity 实现自定义密码策略UserManager 类文档IUserTokenProvider 接口文档

1
调试符号给了我所需的东西。非常感谢!编辑:结果发现“ResetPassword”是这种情况下的正确目的。 - Jeremy Cook

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接