Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get UserId from a PasswordReset token in ASP.NET Identity 2.0?

To reset a password we need to know a UserId and pass it to the UserManager.ResetPasswordAsync method. In the Identity 1.0 it was possible to obtain UserId from the UserManager.PasswordResetTokens.Validate method ((UserManager.PasswordResetTokens.Validate(token)).UserId). Now it's gone and all existing examples telling me that I need to ask an user for username or email. This is not user friendly, I don't want my users enter username again if token is valid.

This is already established tradition in ASP.NET Identity - something that worked before is broken in the new release. Of course I can create my own combined token with embedded UserId, but why I need to do extra work? New releases should improve things, not make them worse.

like image 339
graycrow Avatar asked Mar 31 '14 15:03

graycrow


1 Answers

Asp.Net Identity 2.x do not provide a way to find a user by a token created from GeneratePasswordResetTokenAsync method.

You have two options:

1) Add the user id at the url you will send to the user. Ex:

var token = await _userManager.GeneratePasswordResetTokenAsync(applicationUser);

var callbackUrl = $"/reset-password/?user={WebUtility.UrlEncode(applicationUser.Id)}&code={WebUtility.UrlEncode(token)}";

This approach is more user friendly. But I know people that says this is a security issue because anyone with the link could reset the user password.

2) Ask for the user name at the reset password page, as you did. Ex:

public async Task<YourResultModel> ResetPassword(ResetPasswordViewModel vm)
{
    // Your password validations...

    var user = await _userManager.FindByNameAsync(vm.UserName); 
    // could be FindByEmailAsync if your app uses the user e-mail to login.

    IdentityResult result = await _userManager.ResetPasswordAsync(user, vm.Token, vm.NewPassword);

    return YourResultModelFromIdentityResult(result);
}

Before choose between this two approaches you need to think about your specific scenario. For example: If your app uses the user e-mail as username and to intercept the token the "interceptor" needs to access the user e-mail box, remove the user id from reset password link will not improve the security of your app. Because who has the link already knows the e-mail of the user.

like image 165
Lutti Coelho Avatar answered Oct 14 '22 14:10

Lutti Coelho