Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP Identity GenerateUserTokenAsync(string purpose, TKey userId) purpose options

So a UserManager has a function called GenerateUserTokenAsync(string purpose, TKey userId).

What does this do in ASP Identity? Can I use this to generate OAuth Bearer tokens? Also what is the purpose parameter for? What values can this be?

like image 955
user1613512 Avatar asked Sep 08 '14 06:09

user1613512


2 Answers

UserManager.GenerateUserTokenAsync(User, TokenProvider, Purpose)

can be used to generate Tokens for purposes that are not implemented be the UserManager.

One example could be an invitation system. In a WebProject you need to create a TokenProvider like this:

public class InvitationTokenProvider<TUser> : DataProtectorTokenProvider<TUser> where TUser : class
{
    public InvitationTokenProvider(IDataProtectionProvider dataProtectionProvider, IOptions<InvitationTokenProviderOptions> options, ILogger<DataProtectorTokenProvider<TUser>> logger) : base(dataProtectionProvider, options, logger)
    {

    }
}

and the InvitationTokenProviderOptions

public class InvitationTokenProviderOptions : DataProtectionTokenProviderOptions
{
}

then you can register it in StartUp.ConfigureServices().

services.AddIdentity<User, Role>(options =>
{
    // ...
}).AddEntityFrameworkStores<ApplicationDbContect>()
   .AddDefaultTokenProviders()
   .AddTokenProvider<InvitationTokenProvider<User>>("Invitation");

Afterwards you can use it with the UserManger like this

// create a token    
string token = await _userManager.GenerateUserTokenAsync(user, "Invitation", "Invitation");
// verify it
bool result = await _userManager.VerifyUserTokenAsync(user, "Invitation", "Invitation", token);

If you are going to use the token in URLs, don't forget to make it URL-Safe (it may contain '/' and other symbols. Also check if trailing '==' is lost on the way through emails and browsers.

like image 145
Marius Steinbach Avatar answered Nov 09 '22 05:11

Marius Steinbach


Documentation for 'GenerateUserTokenAsync' says

Get a user token for a specific purpose

This method should not be used directly, (no idea why it is public). It is used in generating password reset token (GeneratePasswordResetTokenAsync) and email confirmation tokens (GenerateEmailConfirmationTokenAsync). And it is used like this:

GenerateUserTokenAsync("Confirmation", userId); // email confirmation

GenerateUserTokenAsync("ResetPassword", userId); // password reset

In default implementation of token provider (TotpSecurityStampBasedTokenProvider) purpose is used as some sort of password in cryptographic token generation.

Overall, you don't need to use GenerateUserTokenAsync, just call GeneratePasswordResetTokenAsync or GenerateEmailConfirmationTokenAsync.

like image 2
trailmax Avatar answered Nov 09 '22 06:11

trailmax