6

Part-2 A Demo On JWT Access Token And Refresh Token Authentication In .NET6 Web...

 2 years ago
source link: https://www.learmoreseekmore.com/2022/06/part2-demo-on-jwt-access-token-and-refresh-token-authentication-in-dotnet6-webapi.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
NestJS%20FileUpload.png

In this article, we will learn the generation and usage of the refresh token in .NET6 Web API application.

Click here to understand the implementation of the JWT token in .NET6 Web API.

Refresh Token:

When the JWT access token expires to renew it without user credentials we will use the Refresh Token.
Let's understand the flow of  Refresh Token.
1.jpg
  • The user sends valid 'User Name' and 'Password' to the server, then the server will generate JWT Access Token and Refresh Token sent as a response
  • The JWT Access Token is a short live token(eg 20 minutes) and Refresh Token is a long live token(eg: 7 days)
  • Now client application sends a JWT access token in the request header that makes the user authenticated.
  • If the JWT token expires then the server returns 401 unauthorized responses.
  • Then the client sends the refresh token to the server to regenerate the JWT Access token. The server validates the refresh token and returns a new JWT Access Token and a new Refresh Token as a response.

RefreshToken Table SQL Script:

In general Refresh, Token value will be saved into the database. Users can logged-in from multiple devices then we shall have the respective token values so let's create a 'RefreshToken' table. In the 'RefreshToken' table a single user can have multiple tokens based on their authentication from the device.
Note: To remove the expired Refresh Tokens it is advised to run a separate background job so that our table contains only active tokens.
Run the below script to create the 'RefreshToken' table.


  1. CREATE TABLE RefreshToken(
  2. [Id] [int] IDENTITY(1,1) NOT NULL,
  3. [UserId] [int] NOT NULL,
  4. [Token] [varchar](1000) NOT NULL,
  5. [ExpirationDate] [datetime] NOT NULL,
  6. CONSTRAINT [PK_RefreshToken] PRIMARY KEY CLUSTERED
  7. [Id] ASC
  8. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  9. ) ON [PRIMARY]

Create Refresh Token:

Along with JWT Access Token, we also need to generate the Refresh Token whereas the refresh token needs to save into the 'RefreshToken' table.
Let's create a private method in the 'AccountService.cs' file for generating the unique refresh token.
Services/AccountService.cs:


  1. private string CreateRefreshToken()
  2. var tokenBytes = RandomNumberGenerator.GetBytes(64);
  3. var refreshtoken = Convert.ToBase64String(tokenBytes);
  4. var tokenIsInUser = _myAuthContext.RefreshToken
  5. .Any(_ => _.Token == refreshtoken);
  6. if (tokenIsInUser)
  7. return CreateRefreshToken();
  8. return refreshtoken;
  • (Line: 3&4) Creating the Refresh Token value using the 'RandNumberGenerator'.
  • (Line: 6&7) Cross-check if the newly created refresh token was already in 'RefreshToken'.
  • (Line: 9-12) If the Refresh token already exists in the database then we are going to execute our method(CreateRefreshToken) again.
  • (Line: 13) Returns unique newly created Refresh Token.

Now let's create a private method to save the newly created Refresh Token value per user into the 'RefreshToken' table.

Services/AccountService.cs:


  1. private async Task InsertRefreshToken(int userId, string refreshtoken)
  2. var newRefreshToken = new RefreshToken
  3. UserId = userId,
  4. Token = refreshtoken,
  5. ExpirationDate = DateTime.Now.AddDays(7)
  6. _myAuthContext.RefreshToken.Add(newRefreshToken);
  7. await _myAuthContext.SaveChangesAsync();
  • Here save 'UserId', 'RefreshToken', 'Refresh Token Expiration Date' into the 'RefreshToken' table.

Now let's update the 'TokenDto.cs' entity.

Dtos/TokenDto.cs:


  1. namespace Dot6.Jwt.API.Dtos;
  2. public class TokenDto
  3. public string AccessToken { get; set; }
  4. public string RefreshToken { get; set; }
  • (Line: 6) Added new property like 'RefreshToken'.

Update the 'GetAuthtokens()' method in the 'AccountService'.

Services/AccountService.cs:


  1. public async Task<TokenDto> GetAuthTokens(LoginDto login)
  2. User user = await _myAuthContext.User
  3. .Where(_ => _.Email.ToLower() == login.Email.ToLower() &&
  4. _.Password == login.Password).FirstOrDefaultAsync();
  5. if (user != null)
  6. var accessToken = CreateJwtToken(user);
  7. var refreshToken = CreateRefreshToken();
  8. await InsertRefreshToken(user.Id, refreshToken);
  9. return new TokenDto
  10. AccessToken = accessToken,
  11. RefreshToken = refreshToken
  12. return null;
  • (Line: 10-17) Here along with JWT Access Token, also generating Refresh Token and return in the response

Step 1:

2.JPG

Step 2:

3.JPG

Usage Of Refresh Token:

On JWT Access Token expiration we can use the Refresh Token to renew the JWT Access Token.
Let's create a payload entity like 'RefreshTokenDto.cs'.
Dtos/RefreshTokenDto.cs:


  1. namespace Dot6.Jwt.API.Dtos;
  2. public class RefreshTokenDto
  3. public string Token { get; set; }

Let's define the method definition to renew the JWT Access token in the 'IAccountService.cs'.

Services/IAccountService.cs:
Task<TokenDto> RenewTokens(RefreshTokenDto refreshToken);

Let's implement the 'RenewTokens' method into the 'AccountService'.

Services/AccountService.cs:


  1. public async Task<TokenDto> RenewTokens(RefreshTokenDto refreshToken)
  2. var userRefreshToken = await _myAuthContext.RefreshToken
  3. .Where(_ => _.Token == refreshToken.Token
  4. && _.ExpirationDate >= DateTime.Now).FirstOrDefaultAsync();
  5. if (userRefreshToken == null)
  6. return null;
  7. var user = await _myAuthContext.User
  8. .Where(_ => _.Id == userRefreshToken.UserId).FirstOrDefaultAsync();
  9. var newJwtToken = CreateJwtToken(user);
  10. var newRefreshToken = CreateRefreshToken();
  11. userRefreshToken.Token = newRefreshToken;
  12. userRefreshToken.ExpirationDate = DateTime.Now;
  13. await _myAuthContext.SaveChangesAsync();
  14. return new TokenDto
  15. AccessToken = newJwtToken,
  16. RefreshToken = newRefreshToken
  • (Line: 3-5) Fetching record from the 'RefreshToken' table.
  • (Line: 7-10) Return empty response if  refresh token is not found in the 'RefreshToken' table
  • (Line: 12&13) Fetching the user information from the 'User' table.
  • (Line: 17&18) Creating new JWT Access Token and Refresh Token.
  • (Line: 20-22) Refresh token need to be used only once, the next new refresh token need to be generated along with the JWT access token. So we have to update our 'RefreshToken' table with the newly generated refresh token value.
  • (Line: 24-28) Returns newly created token as a response.

Let's add the new endpoint for regenerating tokens.

Controllers/AccountController.cs:


  1. [HttpPost]
  2. [Route("renew-tokens")]
  3. public async Task<IActionResult> RenewTokens(RefreshTokenDto refreshToken)
  4. var tokens = await _accountService.RenewTokens(refreshToken);
  5. if (tokens == null)
  6. return ValidationProblem("Invalid Refresh Token");
  7. return Ok(tokens);

Step 1:

4.JPG

Step2:

5.JPG

Support Me!
Buy Me A Coffee PayPal Me

Wrapping Up:

Hopefully, I think this article delivered some useful information on generating JWT tokens in .NET6 Web API. I love to have your feedback, suggestions, and better techniques in the comment section below.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK