Hi @Lavanya Chakkaravel , thank you for the detailed code.
From what I've seen, the problem you're facing is that you're using ASP.NET Core Identity with Entity Framework Core 8 and PostgreSQL, and you'd like to retrieve the refresh token that Identity generates internally.
The catch is—ASP.NET Identity does not generate refresh tokens by default. It manages login, cookie-based sessions, and optionally JWT access tokens, but it doesn’t include refresh token logic unless you implement it yourself.
Here’s how you can implement it:
You’ll need to implement refresh token support manually. Start by creating a model to store refresh tokens:
public class RefreshToken
{
public int Id { get; set; }
public string Token { get; set; }
public string UserId { get; set; }
public IdentityUser User { get; set; }
public DateTime ExpiryDate { get; set; }
public bool IsRevoked { get; set; }
}
Add this to your DbContext:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options) { }
public DbSet<RefreshToken> RefreshTokens { get; set; }
}
Next, during login or token generation, generate and store the refresh token securely:
public async Task<string> GenerateRefreshTokenAsync(IdentityUser user)
{
var refreshToken = new RefreshToken
{
Token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(64)),
UserId = user.Id,
ExpiryDate = DateTime.UtcNow.AddDays(7),
IsRevoked = false
};
_dbContext.RefreshTokens.Add(refreshToken);
await _dbContext.SaveChangesAsync();
return refreshToken.Token;
}
When you authenticate a user, return both the access token and the refresh token:
var accessToken = GenerateAccessToken(user); // Your JWT logic
var refreshToken = await GenerateRefreshTokenAsync(user);
return Ok(new
{
AccessToken = accessToken,
RefreshToken = refreshToken
});
Later, when the access token expires, the client can send the refresh token to an endpoint like /api/token/refresh, where you'll validate the token, check expiry/revocation, and then issue a new access token.
A good implementation guide that mirrors this approach: Using Refresh Tokens in ASP.NET Core Authentication - Code Maze
Helpful documentations you can checkout:
- Identity model customization in ASP.NET Core | Microsoft Learn
- Configure JWT bearer authentication in ASP.NET Core | Microsoft Learn
Hope this helps! Let me know if you need any additional information or help in implementing this.