首页 > 解决方案 > Asp .net core 更改密码需要重新启动应用程序

问题描述

我正在启动我的应用程序,登录并更改我的密码(我使用的是默认的 net .core 身份):

IdentityResult identityResult = 
                await _userManager.ChangePasswordAsync(
                     applicationUser, 
                     model.CurrentPassword, 
                     model.NewPassword);

这可行,并且在数据库中存储了新的哈希密码。

然后,我退出并尝试使用新密码登录。但

if (await _userManager.CheckPasswordAsync(user, password))

返回false。(使用旧密码登录仍然有效,我没有缓存任何内容)

当我重新启动我的应用程序并尝试使用新密码登录时,它可以工作。我猜是那个 PasswordStore 有问题(有缓存吗?)?任何其他我可能忘记的建议或为什么这不起作用?

编辑:

完整的修改密码方法:

[HttpPut]
[Route("api/user/changepassword/{ident}")]
public async Task<bool> ChangePassword(int ident, [FromBody]ChangePasswordModel model)
{
    if (!ModelState.IsValid)
        return false;

    ApplicationUser applicationUser;

    if ((applicationUser = await _userManager.FindByIdAsync(ident.ToString())) == null)
        return false;

    IdentityResult identityResult = await _userManager.ChangePasswordAsync(applicationUser, model.CurrentPassword, model.NewPassword);
    return identityResult.Succeeded;
}

部分来自我的 startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

标签: c#asp.net-coreasp.net-core-identity

解决方案


所以我猜,AspNetCoresUserManager<TUser>缓存数据(我猜它是由 PasswordStore 缓存的?如果错了,请纠正我。)

我可以通过UserManager<TUser>在 tokenprovider-middleware 中验证密码时获取一个新的 -object 来修复它。

private async Task _generateToken(HttpContext context)
{
    StringValues username = context.Request.Form["username"];
    StringValues password = context.Request.Form["password"];

    var usermanager = context.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();

    ApplicationUser user = await usermanager.FindByNameAsync(username);

    if (user == null)
    {
        context.Response.StatusCode = StatusCodes.Status400BadRequest;
        await context.Response.WriteAsync("Invalid username or password.");
        return;
    }

    ClaimsIdentity identity = await _getIdentity(user, password);

    if (identity == null)
    {
        await usermanager.AccessFailedAsync(user);

        context.Response.StatusCode = StatusCodes.Status400BadRequest;
        await context.Response.WriteAsync("Invalid username or password.");
        return;
    }

我可以UserManager<TUser>使用以下扩展方法创建一个新的:

var usermanager = context.RequestServices.GetRequiredService<UserManager<TUser>>();

在验证密码时,我们现在验证新数据并且新密码正确(之前的密码不正确)。


推荐阅读