Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm working with ASP.NET Core Web API application. I'm trying to implement Jwt Token Based Authentication on top of ASP.NET Identity( built in with database tables).

I have implemented all scenarios like register user, login etc but now trying to implement refresh token flow( where access token get expired, client need to get replaced access token using refresh token) . I have seen people are creating new table (refreshToken) to store refresh token so it can be validated with access token and new access and refresh tokens will be generated

https://www.blinkingcaret.com/2018/05/30/refresh-tokens-in-asp-net-core-web-api/

https://www.c-sharpcorner.com/article/handle-refresh-token-using-asp-net-core-2-0-and-json-web-token/

I have created new table(refreshToken) to store refresh token and verify it to generate access token, It works fine but I wanted to see if i can use existing AspNetUserTokens table to handle same scenario. I understand that AspNetUserTokens table is used to confirmation email, forgot password etc.

My question is: if someone has used AspNetUserTokens to store refreshtoken, Please share idea as usermanager class does not expose direct token model(AspNetUserTokens) and not sure if i use IdentityDbContext, what are the pron and cons ? I have implemented IdentityDbContext but i dont see built in class in Microsoft.AspNetCore.Identity to store token in AspNetUserTokens

Would be very grateful for some guidance.

Thank you

like image 585
Ankit Patel Avatar asked Dec 06 '18 20:12

Ankit Patel


1 Answers

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); 
like image 159
Chris Schoon Avatar answered Sep 18 '22 17:09

Chris Schoon