ASP.net Core 2.0 JWT Token Refresh
Asked Answered
O

2

7

I've implemented the JWT Bearer Auth along with the Identity Cookie Auth, one for UI and the other for REST APIs in my .NET Core 2.0 project.

Everything works as of now with the JWT token where I've set the expiry time as 30 mins, the same as the Identity Cookie expiry time.

I've not come across any official docs for the implementation of the refresh tokens for JWT. There are 1 or 2 blog posts though on this topic but they are too complex and high maintenance.

So, wanted to know if the concept of refresh tokens applies here or do we only use the JWT access token ?

On researching, this is the closest I came to an answer SO

Optimism answered 18/10, 2017 at 12:28 Comment(1)
were you able to find a good article/ solution?Curry
M
0

You can use IdentityServer4 which is an OpenID Connect and OAuth 2.0 framework for ASP.NET Core 2 and implements refresh token protocol

Mendel answered 29/3, 2018 at 16:27 Comment(0)
V
-1

I have implemented JWT refresh tokens in one of my projects. Below, I have provided the code for the refresh token mechanism. I hope you find it useful:

using Microsoft.AspNetCore.Authorization; 
using Microsoft.AspNetCore.Mvc; 
using Microsoft.IdentityModel.Tokens; 
using System; 
using System.IdentityModel.Tokens.Jwt; 
using System.Security.Claims; 
using System.Text; 

[ApiController]
[Route("api/[controller]")] 
public class AuthController : ControllerBase 
{
    private readonly string _secretKey = "your_secret_key_here"; // Secret key used for signing the JWT token

    [Authorize] 
    [HttpPost("refresh-token")] // 'api/auth/refresh-token'
    public IActionResult RefreshToken() 
    {
        var tokenHandler = new JwtSecurityTokenHandler(); 
        var key = Encoding.ASCII.GetBytes(_secretKey); 

        // Get current user's claims from the authenticated user's identity
        var claimsIdentity = User.Identity as ClaimsIdentity; 
        var claims = claimsIdentity?.Claims; // Extract the claims from the identity

        // Create new token descriptor with claims and extended expiration time
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims), // Set the subject of the token with the existing claims
            Expires = DateTime.UtcNow.AddMinutes(30), // Set the token expiry time to 30 minutes from now
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) // Set the signing credentials with the secret key
        };

        var token = tokenHandler.CreateToken(tokenDescriptor); // Create the new token based on the descriptor
        var newToken = tokenHandler.WriteToken(token); // Write the token as a string

        return Ok(new { token = newToken }); // Return the new token in the response
    }
}

Vassaux answered 12/7, 2024 at 18:50 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.