I am configuring my application to handle the following scenario: When I create a new user as an admin, a temporary (random) password is generated for that user. After the user logs in for the first time, they are required to change their password. This requirement is tracked using the MustChangePassword field in the AppUser : Identity
class.
I want to enforce that users must change their password immediately after logging in. If the user tries to access any other links, they should be redirected to the Change Password page. I thought configuring middleware would be the best approach for this.
However, with my current configuration (see below), even when I submit the change password form, it still redirects to /Account/ChangePassword.
public class CheckPasswordChangeMiddleware
{
private readonly RequestDelegate _next;
public CheckPasswordChangeMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, UserManager<AppUser> userManager, SignInManager<AppUser> signInManager)
{
if (context.User.Identity.IsAuthenticated)
{
var user = await userManager.GetUserAsync(context.User);
if (user != null && user.MustChangePassword && !context.Request.Path.StartsWithSegments("/Account/ChangePassword"))
{
context.Response.Redirect("/Account/ChangePassword");
return;
}
}
await _next(context);
}
}
Thank you for any help or suggestions!