How to reduce reset token length in Identity Asp.Net?

I use the Asp.Net ID to generate a reset password.

string Token = userManager.GeneratePasswordResetToken(userId); 

the above code gives me a long token. Is it possible to generate a reset password with a short length?

+8
c # asp.net-mvc-4 asp.net-identity
source share
2 answers

Your reset password must be cryptographically random - this means that, given the set of tokens used, the next token should be impossible to guess. It should also cover a sufficiently large set of possible values ​​that brute force tries all of them impractically slowly.

You can make changes so that the latter work with smaller sets of possible values ​​- for example, you can add a delay of 1 with the password reset page / action before checking the marker. Your users will notice a delay on a rarely used page, but attackers will not be able to quickly launch many tokens.

So first you need to get a cryptographically random number:

 var random = new byte[8]; using (var rng = System.Security.Cryptography.RandomNumberGenerator.Create()) rng.GetBytes(random); 

I put 8 bytes here, but you can do it any length.

Then you need to do this in a beautiful copied line. You can do this with a Unicode conversion, but I find base 64 more reliable:

 Convert.ToBase64String(random).TrimEnd('='); 

Using this with bytes 8 , you get 64 bits of possible values ​​and a string of 10 char. Using 4 will give you 32 bits (possibly with a slow token check on a site with a low degree of protection) and 5 char.

0
source share

Replace the long code with a shorter one and save it in the application cache.

When generating:

 var token = UserManager.GeneratePasswordResetToken(user.Id); var guidCode = GenerateCustomToken(); //use this https://stackoverflow.com/a/1668371/631527 CacheHelper.AddToCache(guid, token); //add it to MemoryCache.Default var resetUrl = $"https://.....com/password-reset/{guidCode}/{userName}"; 

When checking:

 //get guidCode from the request in your GET or POST controller var token = CacheHelper.GetValue(guidCode); //retrieve it from cache var result = UserManager.ResetPassword(user.Id, token, model.Password); 
0
source share

All Articles