0

I have a login method, which give me the access and refresh token.

[HttpGet]
[AllowAnonymous]
public IActionResult Login()
{
    var claims = new Claim[]
    {
        new Claim(ClaimTypes.Role, "Administrator")
    };
    var now = DateTime.UtcNow;
    var signingCredentials = new SigningCredentials(
        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.configuration["Key"])), SecurityAlgorithms.HmacSha256);

    var accessToken = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
        claims: claims,
        notBefore: now,
        expires: now.AddMinutes(10),
        signingCredentials: signingCredentials));

    var refreshToken = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
        notBefore: now,
        expires: now.AddYears(2),
        signingCredentials: signingCredentials));

    return Ok(new JwtToken
    {
        AccessToken = accessToken,
        RefreshToken = refreshToken
    }); 
}

And I use the access token with Postman. In the headers:

Bearer eyJhbGciOiJIUzI1...

But after 10 minutes I can't use the API because the access token is rejected. How can I renew the access token with every request to the API (within these 10 minutes)?

Jhon Duck
  • 357
  • 4
  • 14
  • If you refresh the token on every request you will need to change it also on every request with postman? – Isma Apr 10 '18 at 17:21
  • You use the refresh token to renew the access token, and it doesn't need to be within the 10 minutes your access token is valid, but within the time the refresh token is valid. See [this answer](https://stackoverflow.com/questions/44976677/should-i-explicitly-send-the-refresh-token-to-get-a-new-access-token-jwt/44977875#44977875) to get a better understanding of it. I also recommend. In that answer you'll also find a link to a good tutorial esp. for C#/ASP.net. – jps Apr 10 '18 at 19:00

1 Answers1

0

You could set a variable or cookie with the expiry time of the token, then every request that is made you need to check if this expiry is in the past. If it is, you should be able to use the refresh token to get a new access token.

This will ensure you are not getting a token for each request but only when the token expires.

SamBremner
  • 793
  • 2
  • 10
  • 22
  • Good idea, but I have the same problem: how to renew the access token. If the authorization fail, I call to the API for get a new token? – Jhon Duck Apr 10 '18 at 17:39