Details
Generate JWT Tokens
Create a TokenService
class that takes an IConfiguration
and a UserManager<ApplicationUser>
Create a private GenerateAccessToken
method
private string GenerateAccessToken(ApplicationUser user)
{
var key = config.GetValue<string>("Jwt:Key");
var issuer = config.GetValue<string>("Jwt:Issuer");
var audience = config.GetValue<string>("Jwt:Audience");
// Ensure configuration values are not null or empty
if (string.IsNullOrEmpty(key) ||
string.IsNullOrEmpty(issuer) ||
string.IsNullOrEmpty(audience))
{
throw new InvalidOperationException("JWT configuration values are missing.");
}
var securityKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(key));
var credentials = new SigningCredentials(
securityKey, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>
{
new (ClaimTypes.NameIdentifier, user.Id),
new (ClaimTypes.Email, user.Email ?? string.Empty)
};
// Generate token
var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddDays(1),
signingCredentials: credentials);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
return tokenString;
}
Create a private GenerateRefreshToken
method
private static string GenerateRefreshToken()
{
var randomNumber = new byte[32];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(randomNumber);
return Convert.ToBase64String(randomNumber);
}
Then create a public GenerateTokensAsync
method and call both private methods
public async Task<BaseResponse> GenerateTokensAsync(ApplicationUser user)
{
var accessToken = GenerateAccessToken(user);
var refreshToken = GenerateRefreshToken();
user.RefreshToken = refreshToken;
user.RefreshTokenExpiryTime = DateTime.UtcNow.AddDays(30);
var result = await userManager.UpdateAsync(user);
if (result.Succeeded is false)
{
return new BaseResponse()
{
Succeeded = false,
Message = "Failed to generate tokens.",
Data = new { result.Errors }
};
}
return new BaseResponse()
{
Succeeded = true,
Message = "Successfully generated tokens.",
Data = new
{
accessToken,
refreshToken
}
};
}
Then register the service with dependency injection
services.AddScoped<TokenService>();
Then use it like any other service!