Using AspNetUserTokens table to store refresh token in ASP.NET Core Web Api

I’ll answer your question directly then propose an alternative. You can Remove, Set, Get, and Validate tokens with the AspNetUserTokens table. However, you can probably skip the db and I’ll describe that below.

The following methods of the UserManager will generate and store:

await _userManager.RemoveAuthenticationTokenAsync(user, "MyApp", "RefreshToken");
var newRefreshToken = await _userManager.GenerateUserTokenAsync(user, "MyApp", "RefreshToken");
await _userManager.SetAuthenticationTokenAsync(user, "MyApp", "RefreshToken", newRefreshToken);

The following methods of the UserManager will get and validate:

var refreshToken = await _userManager.GetAuthenticationTokenAsync(user, "MyApp", "RefreshToken");
var isValid = await _userManager.VerifyUserTokenAsync(user, "MyApp", "RefreshToken", refreshToken );

You will need to set up a provider like this using the IdentityBuilder in Startup.

identity.AddTokenProvider("MyApp", typeof(DataProtectorTokenProvider<User>)

As an alternative to storing these tokens in the database, you can use the following to invalidate all tokens as needed. You might do this as a part of Logout.

_userManager.UpdateSecurityStampAsync(user);

Leave a Comment