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 Postman collection. 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class User { public string Username { get; set; } public string Password { get; set; } } public class RefreshToken { public string Username { get; set; } public string Token { get; set; } public bool Revoked { get; set; } } public class JsonWebToken { public string AccessToken { get; set; } public string RefreshToken { get; set; } public long Expires { 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:
1 2 3 4 5 6 7 |
public interface IAccountService { void SignUp(string username, string password); JsonWebToken SignIn(string username, string password); JsonWebToken RefreshAccessToken(string token); void RevokeRefreshToken(string token); } |
Into my AccountService implementation, I’ll inject the following services:
1 2 3 4 5 |
public AccountService(IJwtHandler jwtHandler, IPasswordHasher<User> passwordHasher) { _jwtHandler = jwtHandler; _passwordHasher = passwordHasher; } |
The IJwtHandler (which is responsible for generating JSON Web Tokens) can be found in a repository and the IPasswordHasher
Let’s focus now on refreshing and revoking the tokens:
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 |
public JsonWebToken RefreshAccessToken(string token) { var refreshToken = GetRefreshToken(token); if (refreshToken == null) { throw new Exception("Refresh token was not found."); } if (refreshToken.Revoked) { throw new Exception("Refresh token was revoked"); } var jwt = _jwtHandler.Create(refreshToken.Username);; jwt.RefreshToken = refreshToken.Token; return jwt; } public void RevokeRefreshToken(string token) { var refreshToken = GetRefreshToken(token); if (refreshToken == null) { throw new Exception("Refresh token was not found."); } if (refreshToken.Revoked) { throw new Exception("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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public JsonWebToken SignIn(string username, string password) { var user = GetUser(username); if (user == null) { throw new Exception("Invalid credentials."); } var jwt = _jwtHandler.Create(user.Username); var refreshToken = _passwordHasher.HashPassword(user, Guid.NewGuid().ToString()) .Replace("+", string.Empty) .Replace("=", string.Empty) .Replace("/", string.Empty); jwt.RefreshToken = refreshToken; _refreshTokens.Add(new RefreshToken { Username = username, Token = refreshToken }); return jwt; } |
It’s up to you how the refresh token is going to look like, I decided to create a unique GUID and then make use of IPasswordHasher to create a secure, random string.
And pretty much that’s it, we can define the following controller in our API to see if everything works as expected:
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 31 32 33 34 35 36 37 38 39 40 |
public class AccountController : Controller { private readonly IAccountService _accountService; public AccountController(IAccountService accountService) { _accountService = accountService; } [HttpGet("account")] public IActionResult Get([FromBody] SignUp request) => Content($"Hello {User.Identity.Name}"); [HttpPost("sign-up")] [AllowAnonymous] public IActionResult SignUp([FromBody] SignUp request) { _accountService.SignUp(request.Username, request.Password); return NoContent(); } [HttpPost("sign-in")] [AllowAnonymous] public IActionResult SignIn([FromBody] SignIn request) => Ok(_accountService.SignIn(request.Username, request.Password)); [HttpPost("tokens/{token}/refresh")] [AllowAnonymous] public IActionResult RefreshAccessToken(string token) => Ok(_accountService.RefreshAccessToken(token)); [HttpPost("tokens/{token}/revoke")] public IActionResult RevokeRefreshToken(string token) { _accountService.RevokeRefreshToken(token); return NoContent(); } } |
Mimo, że na codzień tylko konsumuje Rest API, to wpis bardzo ciekawy i prosty w zrozumieniu.
U nas backend też wykorzystuje tego typu rozwiązania, także wpis bardzo przydatny.
Dzięki, miał być możliwie prosty do zrozumienia.
Pingback: Dew Drop - December 8, 2017 (#2620) - Morning Dew
This is sooooo irritating. I can find anything on this website.
Nice job, now imagine the with Identity Server 4!
Thanks, I haven’t work with IS4, though.
Thanks for the write-up! Lots of information out there on JWTs, but limited implementations for Refresh Tokens. I found this article incredibly helpful (:
Hi Danny,
Had the same issue, that’s why I decided to figure it on my own :).
i like this refresh token. I think u need to try a new code.
Hope you have more great article like that.
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.
Thanks for sharing this marvelous post. I m very pleased to read this article.Sign in pogo
so bad
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
Pogo technical Support Thanks for sharing this marvelous post. I m very pleased to read this article.
phhh. The topic about JWT refresh tokens didn’t covered at all.
Very high level overview without meaningful things about where to store refreshtoken,
GetRefreshToken method is not implemented here.
Waste my time and move away from the right solution like this f.e.
https://blogs.ibs.com/2017/12/19/token-based-auth-in-asp-net-core-2-part-2-refresh-tokens/
Storing the token is barely an implementation detail, and there’s no point to include such code in a blog post, that can be easily added by anyone.
You can find the code for MongoDB storage e.g. here https://github.com/devmentors/DNC-DShop.Services.Identity/blob/master/src/DShop.Services.Identity/Services/RefreshTokenService.cs.
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.
Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative.
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.
Thanks to this article I can learn more. Expand your knowledge and abilities. Actually the article is very practical.
McAfee Support Number
You can download the best happy valentines day my love images
Thanks for this informative content. It’s really good. Actually, I want to share some thoughts and reviews about an Australian assignment help company in Australia and the brand name is SAMPLE ASSIGNMENT
Amazing! Its genuinely awesome article, I have got much clear idea about from this piece of writing.
Would you like your brain activities to be amped up throughout the entire day? One such compound in the market today is Armodafinil. It is the enhanced form of the Nootropic compound Modafinil which also lasts longer, for around 15 hours. Buy Nuvigil online with free shipping from Online Pharmacy Pills. Get the best quality meds for your mental health. Visit Online Pharmacy Pills with benefits like free shipping and additional pills for our regular customers.
They are relatively few free GPS TOPO maps accessible from Garmin as of now, in spite of the fact that there is periodically a free map download accessible as an advancement. So as to see the most recent free Garmin TOPO maps at that point ensure you visit their site and investigate the Outdoor Handheld GPS Mapping segment that they have on there.
Click For More Information:https://www.garminmapupdate-s.com/garmin-map-updates/
valentines day meme valentines day
Hello,
Today many people work in blogging and interested to build career there. we do face some problem to do that. we often make some mistake and this content and tips will help us a lot to do that.
Thanks
Visit Our Blog :-
https://www.datinghelpus.com/how-do-i-cancel-my-silversingles-membership/
This blog is awesome. HP has altered the universe of innovation through its items which have the best highlights and innovation. These laptops and PCs are easy to use and the organization has dealt with each necessity which its clients have and has given its items in reasonable ranges as well. If you have any kind of issue or problem related to HP Support Number then in that case you can visit our website
Website- http://www.hphelpnumber.net/hp-support/
its a very helpful blog thanks for sharing if you need any type of help regarding Hp products like NETWORK SCANNER ERROR IN HP then in that situation visit our website. https://www.helptechnumber.com/how-to-fix-network-scanner-error-in-hp-printers/
Thanks for sharing Nice and good blog if you need any type of help regarding Dell printer like CONNECT DELL PRINTER WIRELESS SYSTEM then in that situation visit our website.
https://www.fix1st.com/printers-support/how-can-you-connect-dell-printer-to-a-wireless-system/
It’s an innovative and informative blog thanks for sharing. if you are having any type of issue regarding Rand McNally Update then visit our
website.http://www.randmcnallyupdates.com/support/rand-mcnally-tablet-tnd70-tnd80-update-support/
Unique and expressive blog. Thanks for sharing, helped a lot in my query. If you are trying to Transfer Email from Incredimail to Windows Live Mail and you are facing any problem to Transfer Emails then you may connect with the experts through Incredimail Technical Support Number or visit the website.
If you are searching help for Some of the Common Issues Bitdefender error code 1002 then you may visit our website. We are going to give the best outputs as the blogs are helpful & convenient for the users. In the same way, for more help you may call at Bitdefender Customer support.
Unique and Expressive blog. helped a lot in my query. if you are visitor in Seattle and you require high profile Car Rental Seattle Airport service then you may visit our website. You will find variety of vehicles to select on our website. Just visit, http://www.carrentalseattle.us/
Confidently depend upon us to read that latest updates regarding all leading dating website. This portal is free to access.
Individual research for each dating site is now not required to arrange the required info. Highly competent dating help us is here to help in a stupendous way. Over this nicely-configured portal, you will read confirm details about all policies and latest updates. Visit to this website is the easiest way to get hands on authentic details. Therefore, you are advised to not consider other kinds of implementations. http://www.samadhantutors.com/
Confidently depend upon us to read that latest updates regarding all leading dating website. This portal is free to access.
Individual research for each dating site is now not required to arrange the required info. Highly competent dating elp s is here to help in a stupendous way. Over this nicely-configured portal, you will read confirm details about all policies and latest updates. Visit to this website is the easiest way to get hands on authentic details. Therefore, you are advised to not consider other kinds of implementations.http://idltechnologies.com/
Confidently depend upon us to read that latest updates regarding all leading dating website. This portal is free to access.
Individual research for each dating site is now not required to arrange the required info. Highly competent datin helpus is here to help in a stupendous way. Over this nicely-configured portal, you will read confirm details about all policies and latest updates. Visit to this website is the easiest way to get hands on authentic details. Therefore, you are advised to not consider other kinds of implementations. https://worldcoolcare.com/ac-repairing/
Hello,
I would say this is one of the best article I’ve read.. From beginning to end you nailed it totally. To write this you might have worked hard for research.Thanks for sharing this good article.
Thank you.
Visit Our Website :- https://www.customerinterations.com/uber-customer-service/
A simple guide for resolved all kind of Ourtime.com bungles very swiftly and effectively by Dating Help US
https://www.datinghelpus.com/ourtime-customer-service/
Be that as it may, in the 1 case they’re not, you can totally screw somebody over. Show bolster operators the ip address of the individual associating. Is it a typical one? Is it a VPN/tor one? and so forth. Give them a notice to be suspicious.
Thank for sharing such a valuable blog. Your blog is entirely dependable for new perusers. My name is Linda Williams; I am a full-time blogger at Dial Printer Support. I have additionally composed a blog on various points. You can visit us at: Printer Technical Support https://technotalks.webflow.io Printer Customer Support Florida