Search code examples
asp.net-identityasp.net-authorizationasp.net-authentication

ApplicationUserManager's Generate ___ Token methods


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!


Solution

  • 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.