ApplicationUserManager's Generate ___ Token me

2019-08-21 02:44发布

问题:

I see there are 5 different Generate Token methods on ApplicationUserManager such as:

  • manager.GenerateChangePhoneNumberToken()
  • manager.GenerateEmailConfirmationToken()
  • manager.GeneratePasswordResetToken()
  • manager.GenerateTwoFactorToken()
  • manager.GenerateUserToken()

What is the point of GenerateUserToken when the other 4 exist? When would you only use GenerateUserToken and not any of the others?

Can the UserToken from GenerateUserToken be used instead of the other 4 for all possible token requested tasks?

Trying to understand these better but not finding much help through searching. Thanks!

回答1:

If you look on the source code of UserManager, you'll see that GenerateUserTokenAsync(string purpose, TKey userId) is the one with most logic. All other methods you talk about are a shortcuts for this method with parameter purpose specified.

So when you need to reset password you call GeneratePasswordResetTokenAsync(TKey userId) that in turn calls GenerateUserTokenAsync("ResetPassword", userId).

This purpose parameter is encoded in the token and on the way back, when the token is verified, this purpose must be the same as it was for token generation. I.e. token generated for password reset will not work for email confirmation.