Introduction

In this article , you will learn how to deal with the refresh token when you use jwt (JSON Web Token) as your access_token.

Backgroud

Many people choose jwt as their access_token when the client sends a request to the Resource Server.

However, before the client sends a request to the Resource Server, the client needs to get the access_token from the Authorization Server. After receiving and storing the access_token, the client uses access_token to send a request to the Resource Server.

But as all we know, the expired time for a jwt is too short. And we do not require the users to pass their name and password once more! At this time, the refresh_token provides a vary convenient way that we can use to exchange a new access_token.

The normal way may be as per the following.

ASP.NET Core

I will use ASP.NET Core 2.0 to show how to do this work.

Requirement first

You need to install the SDK of .NET Core 2.0 preview and the VS 2017 preview.

Now, let's begin!

First of all, building a Resource Server

Creating an ASP.NET Core Web API project.

Edit the Program class to specify the url when we visit the API.

  1. public class Program
  2. {
  3. public static void Main(string[] args)
  4. {
  5. BuildWebHost(args).Run();
  6. }
  7. public static IWebHost BuildWebHost(string[] args) =>
  8. WebHost.CreateDefaultBuilder(args)
  9. .UseStartup<Startup>()
  10. .UseUrls("http://localhost:5002")
  11. .Build();
  12. }

Add a private method in Startup class which configures the jwt authorization. There are some differences when we use the lower version of .NET Core SDK.

  1. public void ConfigureJwtAuthService(IServiceCollection services)
  2. {
  3. var audienceConfig = Configuration.GetSection("Audience");
  4. var symmetricKeyAsBase64 = audienceConfig["Secret"];
  5. var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
  6. var signingKey = new SymmetricSecurityKey(keyByteArray);
  7. var tokenValidationParameters = new TokenValidationParameters
  8. {
  9. // The signing key must match!
  10. ValidateIssuerSigningKey = true,
  11. IssuerSigningKey = signingKey,
  12. // Validate the JWT Issuer (iss) claim
  13. ValidateIssuer = true,
  14. ValidIssuer = audienceConfig["Iss"],
  15. // Validate the JWT Audience (aud) claim
  16. ValidateAudience = true,
  17. ValidAudience = audienceConfig["Aud"],
  18. // Validate the token expiry
  19. ValidateLifetime = true,
  20. ClockSkew = TimeSpan.Zero
  21. };
  22. services.AddAuthentication(options =>
  23. {
  24. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  25. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  26. })
  27. .AddJwtBearerAuthentication(o =>
  28. {
  29. o.TokenValidationParameters = tokenValidationParameters;
  30. });
  31. }

And, we need to use this method in the ConfigureServices method.

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. //configure the jwt
  4. ConfigureJwtAuthService(services);
  5. services.AddMvc();
  6. }

Do not forget touse the authentication in the Configure method.

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  2. {
  3. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  4. loggerFactory.AddDebug();
  5. //use the authentication
  6. app.UseAuthentication();
  7. app.UseMvc();
  8. }

The last step of our Resource Server is to edit the ValueController so that we can use the authentication when we visit this API.

  1. [Route("api/[controller]")]
  2. public class ValuesController : Controller
  3. {
  4. // GET api/values/5
  5. [HttpGet("{id}")]
  6. [Authorize]
  7. public string Get(int id)
  8. {
  9. return "visit by jwt auth";
  10. }
  11. }

Turn to the Authentication Server

How to design the authentication?

Here is my point of view,

When the client uses the parameters to get an access_token , the client needs to pass the parameters in the querystring are as follow:

Parameter Value
grant_type the value must be password
client_id the client_id is assigned by manager
client_secret the client_secret is assigned by manager
username the name of the user
password the password of the user

When the client use the parameters to refresh a expired access_token , the client need to pass the parameters in the querystring are as follow,

Parameter Value
grant_type the value must be refresh_token
client_id the client_id is assigned by manager
client_secret the client_secret is assigned by manager
refresh_token after authentication the server will return a refresh_token

Here is the implementation!

Create a new ASP.NET Core project and a new controller named TokenController.

  1. [Route("api/token")]
  2. public class TokenController : Controller
  3. {
  4. //some config in the appsettings.json
  5. private IOptions<Audience> _settings;
  6. //repository to handler the sqlite database
  7. private IRTokenRepository _repo;
  8. public TokenController(IOptions<Audience> settings, IRTokenRepository repo)
  9. {
  10. this._settings = settings;
  11. this._repo = repo;
  12. }
  13. [HttpGet("auth")]
  14. public IActionResult Auth([FromQuery]Parameters parameters)
  15. {
  16. if (parameters == null)
  17. {
  18. return Json(new ResponseData
  19. {
  20. Code = "901",
  21. Message = "null of parameters",
  22. Data = null
  23. });
  24. }
  25. if (parameters.grant_type == "password")
  26. {
  27. return Json(DoPassword(parameters));
  28. }
  29. else if (parameters.grant_type == "refresh_token")
  30. {
  31. return Json(DoRefreshToken(parameters));
  32. }
  33. else
  34. {
  35. return Json(new ResponseData
  36. {
  37. Code = "904",
  38. Message = "bad request",
  39. Data = null
  40. });
  41. }
  42. }
  43. //scenario 1 : get the access-token by username and password
  44. private ResponseData DoPassword(Parameters parameters)
  45. {
  46. //validate the client_id/client_secret/username/passwo
  47. var isValidated = UserInfo.GetAllUsers().Any(x => x.ClientId == parameters.client_id
  48. && x.ClientSecret == parameters.client_secret
  49. && x.UserName == parameters.username
  50. && x.Password == parameters.password);
  51. if (!isValidated)
  52. {
  53. return new ResponseData
  54. {
  55. Code = "902",
  56. Message = "invalid user infomation",
  57. Data = null
  58. };
  59. }
  60. var refresh_token = Guid.NewGuid().ToString().Replace("-", "");
  61. var rToken = new RToken
  62. {
  63. ClientId = parameters.client_id,
  64. RefreshToken = refresh_token,
  65. Id = Guid.NewGuid().ToString(),
  66. IsStop = 0
  67. };
  68. //store the refresh_token
  69. if (_repo.AddToken(rToken))
  70. {
  71. return new ResponseData
  72. {
  73. Code = "999",
  74. Message = "OK",
  75. Data = GetJwt(parameters.client_id, refresh_token)
  76. };
  77. }
  78. else
  79. {
  80. return new ResponseData
  81. {
  82. Code = "909",
  83. Message = "can not add token to database",
  84. Data = null
  85. };
  86. }
  87. }
  88. //scenario 2 : get the access_token by refresh_token
  89. private ResponseData DoRefreshToken(Parameters parameters)
  90. {
  91. var token = _repo.GetToken(parameters.refresh_token, parameters.client_id);
  92. if (token == null)
  93. {
  94. return new ResponseData
  95. {
  96. Code = "905",
  97. Message = "can not refresh token",
  98. Data = null
  99. };
  100. }
  101. if (token.IsStop == 1)
  102. {
  103. return new ResponseData
  104. {
  105. Code = "906",
  106. Message = "refresh token has expired",
  107. Data = null
  108. };
  109. }
  110. var refresh_token = Guid.NewGuid().ToString().Replace("-", "");
  111. token.IsStop = 1;
  112. //expire the old refresh_token and add a new refresh_token
  113. var updateFlag = _repo.ExpireToken(token);
  114. var addFlag = _repo.AddToken(new RToken
  115. {
  116. ClientId = parameters.client_id,
  117. RefreshToken = refresh_token,
  118. Id = Guid.NewGuid().ToString(),
  119. IsStop = 0
  120. });
  121. if (updateFlag && addFlag)
  122. {
  123. return new ResponseData
  124. {
  125. Code = "999",
  126. Message = "OK",
  127. Data = GetJwt(parameters.client_id, refresh_token)
  128. };
  129. }
  130. else
  131. {
  132. return new ResponseData
  133. {
  134. Code = "910",
  135. Message = "can not expire token or a new token",
  136. Data = null
  137. };
  138. }
  139. }
  140. //get the jwt token
  141. private string GetJwt(string client_id, string refresh_token)
  142. {
  143. var now = DateTime.UtcNow;
  144. var claims = new Claim[]
  145. {
  146. new Claim(JwtRegisteredClaimNames.Sub, client_id),
  147. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
  148. new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64)
  149. };
  150. var symmetricKeyAsBase64 = _settings.Value.Secret;
  151. var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
  152. var signingKey = new SymmetricSecurityKey(keyByteArray);
  153. var jwt = new JwtSecurityToken(
  154. issuer: _settings.Value.Iss,
  155. audience: _settings.Value.Aud,
  156. claims: claims,
  157. notBefore: now,
  158. expires: now.Add(TimeSpan.FromMinutes(2)),
  159. signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256));
  160. var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
  161. var response = new
  162. {
  163. access_token = encodedJwt,
  164. expires_in = (int)TimeSpan.FromMinutes(2).TotalSeconds,
  165. refresh_token = refresh_token,
  166. };
  167. return JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented });
  168. }
  169. }

Both above two scenarios only use one action , because the parameters are similar.

When the grant_type is password ,we will create a refresh_token and store this refresh_token to the sqlite database. And return the jwt toekn to the client.

When the grant_type is refresh_token ,we will expire or delete the old refresh_token which belongs to this client_id and store a new refresh_toekn to the sqlite database. And return the new jwt toekn to the client.

Note

I use a GUID as my refresh_token , because GUID is more easier to generate and manager , you can use a more complex value as the refresh token.

At last , Create a console app to test the refresh token.

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. HttpClient _client = new HttpClient();
  6. _client.DefaultRequestHeaders.Clear();
  7. Refresh(_client);
  8. Console.Read();
  9. }
  10. private static void Refresh(HttpClient _client)
  11. {
  12. var client_id = "100";
  13. var client_secret = "888";
  14. var username = "Member";
  15. var password = "123";
  16. var asUrl = $"http://localhost:5001/api/token/auth?grant_type=password&client_id={client_id}&client_secret={client_secret}&username={username}&password={password}";
  17. Console.WriteLine("begin authorizing:");
  18. HttpResponseMessage asMsg = _client.GetAsync(asUrl).Result;
  19. string result = asMsg.Content.ReadAsStringAsync().Result;
  20. var responseData = JsonConvert.DeserializeObject<ResponseData>(result);
  21. if (responseData.Code != "999")
  22. {
  23. Console.WriteLine("authorizing fail");
  24. return;
  25. }
  26. var token = JsonConvert.DeserializeObject<Token>(responseData.Data);
  27. Console.WriteLine("authorizing successfully");
  28. Console.WriteLine($"the response of authorizing {result}");
  29. Console.WriteLine("sleep 2min to make the token expire!!!");
  30. System.Threading.Thread.Sleep(TimeSpan.FromMinutes(2));
  31. Console.WriteLine("begin to request the resouce server");
  32. var rsUrl = "http://localhost:5002/api/values/1";
  33. _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.access_token);
  34. HttpResponseMessage rsMsg = _client.GetAsync(rsUrl).Result;
  35. Console.WriteLine("result of requesting the resouce server");
  36. Console.WriteLine(rsMsg.StatusCode);
  37. Console.WriteLine(rsMsg.Content.ReadAsStringAsync().Result);
  38. //refresh the token
  39. if (rsMsg.StatusCode == HttpStatusCode.Unauthorized)
  40. {
  41. Console.WriteLine("begin to refresh token");
  42. var refresh_token = token.refresh_token;
  43. asUrl = $"http://localhost:5001/api/token/auth?grant_type=refresh_token&client_id={client_id}&client_secret={client_secret}&refresh_token={refresh_token}";
  44. HttpResponseMessage asMsgNew = _client.GetAsync(asUrl).Result;
  45. string resultNew = asMsgNew.Content.ReadAsStringAsync().Result;
  46. var responseDataNew = JsonConvert.DeserializeObject<ResponseData>(resultNew);
  47. if (responseDataNew.Code != "999")
  48. {
  49. Console.WriteLine("refresh token fail");
  50. return;
  51. }
  52. Token tokenNew = JsonConvert.DeserializeObject<Token>(responseDataNew.Data);
  53. Console.WriteLine("refresh token successful");
  54. Console.WriteLine(asMsg.StatusCode);
  55. Console.WriteLine($"the response of refresh token {resultNew}");
  56. Console.WriteLine("requset resource server again");
  57. _client.DefaultRequestHeaders.Clear();
  58. _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenNew.access_token);
  59. HttpResponseMessage rsMsgNew = _client.GetAsync("http://localhost:5002/api/values/1").Result;
  60. Console.WriteLine("the response of resource server");
  61. Console.WriteLine(rsMsgNew.StatusCode);
  62. Console.WriteLine(rsMsgNew.Content.ReadAsStringAsync().Result);
  63. }
  64. }
  65. }

We should pay attention to the request of the Resource Server!

We must add a HTTP header when we send a HTTP request : `Authorization:Bearer token`

Now , using the dotnet CLI command to run our three projects.

Here is the screenshot of the runninng result.

ASP.NET Core

Note

Summary

This article introduced an easy way to handle the refresh_token when you use jwt. Hope this will help you to understand how to deal with the tokens.