JWT refresh tokens and .NET Core

In this article, I will present to you a basic implementation of the refresh token mechanism that you can extend to your own needs.

Let’s start with the need of using the refresh tokens. When you make use of the token authentication (e.g. OAuth) and pass the tokens via Authorization HTTP header, usually, these tokens have a specific expiration time. Whether it’s a minute, 10 minutes, an hour or a week makes no big difference, as long as you can provide a way to generate the new token.

Most likely, you don’t want the user to login every time that the token expiration hits its limit. On the other hand, you don’t want to store the user credentials (email, login, password etc.) somewhere in memory (whether it’s a device, cookie or a local storage). What can you do then? Store the so-called refresh tokens instead, that can be used to recreate the access tokens.

You can download the whole sample by cloning a repository and the HTTP requests available as the Postmancollection. Now, let’s start with the implementation, just beware that I’m not following here any specialized patterns, rich domain models and so on – it’s just a sample that works, not a sophisticated solution.

At first, let’s start with the models that we’re going to use:

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

publicclassUser

{

publicstringUsername{get;set;}

publicstringPassword{get;set;}

}

publicclassRefreshToken

{

publicstringUsername{get;set;}

publicstringToken{get;set;}

publicboolRevoked{get;set;}

}

publicclassJsonWebToken

{

publicstringAccessToken{get;set;}

publicstringRefreshToken{get;set;}

publiclongExpires{get;set;}

}

These should be rather straightforward. You might also notice, that we will be able to revoke the refresh token, so it can’t be used anymore if the user wishes so.

This is how we could define the business logic:

C#

1

2

3

4

5

6

7

publicinterfaceIAccountService

{

voidSignUp(stringusername,stringpassword);

JsonWebToken SignIn(stringusername,stringpassword);

JsonWebToken RefreshAccessToken(stringtoken);

voidRevokeRefreshToken(stringtoken);

}

Into my AccountService implementation, I’ll inject the following services:

The IJwtHandler (which is responsible for generating JSON Web Tokens) can be found in a repository and the IPasswordHasher comes from Microsoft.AspNetCore.Identity namespace.

Let’s focus now on refreshing and revoking the tokens:

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

publicJsonWebToken RefreshAccessToken(stringtoken)

{

varrefreshToken=GetRefreshToken(token);

if(refreshToken==null)

{

thrownewException("Refresh token was not found.");

}

if(refreshToken.Revoked)

{

thrownewException("Refresh token was revoked");

}

varjwt=_jwtHandler.Create(refreshToken.Username);;

jwt.RefreshToken=refreshToken.Token;

returnjwt;

}

publicvoidRevokeRefreshToken(stringtoken)

{

varrefreshToken=GetRefreshToken(token);

if(refreshToken==null)

{

thrownewException("Refresh token was not found.");

}

if(refreshToken.Revoked)

{

thrownewException("Refresh token was already revoked.");

}

refreshToken.Revoked=true;

}

The logic is very simple here – just ensure that the refresh token exists and that it was not already revoked, so it can be used again and again. And when to create a new refresh token? For example, when the user authenticates:

Fabulous blog. Very well described this informative post by the author. Thanks.
Fix your technical problem with Fixingblog. We are also providing help for Belkin range.If you have any problem With Router, Range Extender, Antivirus etc.

Before you plan to install antivirus software on your device, you are required to take
few important steps to avoid software conflicts with the previously installed versions. please visit
norton activation key

Anyway, Piotr, I don’t want be annoying, and appreciate you willigness to share thougths across the internet.
The question – who is the audience your post ?
a) the person, who doesn’t familiar deeply with the workflow of OAuth2 and wants quickly integrate this technology into own project? – so no, a lot of meaningful steps are missing.
b) the person, who familiar with OAuth2 workflow and wants to find some knowledge gaps, f.e. implementation of refresh token flow? – no, this post covers only high level contracts (AccountController, IAccountService) without any IMPORTANT implementation details of JWT token and refresh token(as post titled).

So, post looks mostly, like a note (some reminder) personally for you, because I have wasted more, than “4 minutes to read” and have tried to find coherence of your pieces of code.

It has nothing to do with the OAuth2, which is huge and complicated.The point was to show what refreshing token is all about, and how easily you can implement it, given that you use JWT which is a good fit for most apps. There’s a link to the repository where you can clone the working code, and if by important details you mean missing implementation of SQL repository (or any other data persistence system), well, that’s not really important.

Great article. I do have a questions about the “Expires” property in the JsonWebToken class though. Is it really necessary? My understanding is that when a 401 is received with “invalid_token” using the “access_token” then you send the “refresh_token” to the auth server to get another “access_token”. Is “Expires” really ever needed or used?

Thanks. “Expires” is just a helper property, for example, the end user might use it in order to periodically ask for a new access token before it’s already expired (simply avoid a few unnecessary “401 unauthorized” requests), but that’s all.

I am confused by your post, I tried to download the solution but I get an error: {“message”:”It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketFailure on PING”}.

What confuses me is are you using your refresh token for everything, most articles I seen that don’t have a refresh token have first something that generates the token with all the claims in it, I don’t see anything about claims in your solution, nor how to store the refresh tokens.

Good article and neat implementation. However, it has one security flaw. You are not renewing the refresh token which is bad according to me. If someone get hold of the refresh token, they can easily generate the access token anytime. Unless off-course if its not revoked.

Many students face the problem of stress in college. Our expert guides dependably work in a state of harmony with the necessities given to us But if you take assignment help, it can let you understand the things at your own speed.

Tramadol Pills is its complex composition which changes the way our brain responds to the nervous system. If any of the health conditions stated above relates to you then visit our website and Buy Tramadol Online. A fully satisfactory and guaranteed result is assured by Online Pharmacy Pills.