(feature): GenerateToken method update

This commit is contained in:
Maksym Sadovnychyy 2024-09-26 21:45:46 +02:00
parent e4da2e68b3
commit 4a6e89c350
3 changed files with 36 additions and 7 deletions

View File

@ -184,7 +184,7 @@ double expiration = 30; // Token expiration in minutes
string username = "user123"; string username = "user123";
List<string> roles = new List<string> { "Admin", "User" }; List<string> roles = new List<string> { "Admin", "User" };
string token = JwtGenerator.GenerateToken(secret, issuer, audience, expiration, username, roles); (string token, JWTTokenClaims claims) = JwtGenerator.GenerateToken(secret, issuer, audience, expiration, username, roles);
Console.WriteLine("Generated JWT Token: " + token); Console.WriteLine("Generated JWT Token: " + token);
``` ```

View File

@ -8,7 +8,7 @@
<!-- NuGet package metadata --> <!-- NuGet package metadata -->
<PackageId>MaksIT.Core</PackageId> <PackageId>MaksIT.Core</PackageId>
<Version>1.0.3</Version> <Version>1.0.4</Version>
<Authors>Maksym Sadovnychyy</Authors> <Authors>Maksym Sadovnychyy</Authors>
<Company>MAKS-IT</Company> <Company>MAKS-IT</Company>
<Product>MaksIT.Core</Product> <Product>MaksIT.Core</Product>

View File

@ -11,18 +11,25 @@ namespace MaksIT.Core.Security;
public class JWTTokenClaims { public class JWTTokenClaims {
public required string? Username { get; set; } public required string? Username { get; set; }
public required List<string>? Roles { get; set; } public required List<string>? Roles { get; set; }
public DateTime? IssuedAt { get; set; }
public DateTime? ExpiresAt { get; set; }
} }
public static class JwtGenerator { public static class JwtGenerator {
public static string GenerateToken(string secret, string issuer, string audience, double expiration, string username, List<string> roles) { public static (string, JWTTokenClaims) GenerateToken(string secret, string issuer, string audience, double expiration, string username, List<string> roles) {
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)); var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
var credentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var credentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var issuedAt = DateTime.UtcNow;
var expiresAt = issuedAt.AddMinutes(expiration);
var claims = new List<Claim> var claims = new List<Claim>
{ {
new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.Name, username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(issuedAt).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(expiresAt).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
}; };
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
@ -35,7 +42,18 @@ public static class JwtGenerator {
signingCredentials: credentials signingCredentials: credentials
); );
return new JwtSecurityTokenHandler().WriteToken(token); var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
// Create the JWTTokenClaims object
var tokenClaims = new JWTTokenClaims {
Username = username,
Roles = roles,
IssuedAt = issuedAt,
ExpiresAt = expiresAt
};
return (jwtToken, tokenClaims);
} }
@ -61,15 +79,26 @@ public static class JwtGenerator {
var username = principal?.Identity?.Name; var username = principal?.Identity?.Name;
var roles = principal?.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value).ToList(); var roles = principal?.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value).ToList();
return new JWTTokenClaims {
var issuedAtClaim = principal?.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Iat)?.Value;
var expiresAtClaim = principal?.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value;
DateTime? issuedAt = issuedAtClaim != null ? DateTimeOffset.FromUnixTimeSeconds(long.Parse(issuedAtClaim)).UtcDateTime : (DateTime?)null;
DateTime? expiresAt = expiresAtClaim != null ? DateTimeOffset.FromUnixTimeSeconds(long.Parse(expiresAtClaim)).UtcDateTime : (DateTime?)null;
return new JWTTokenClaims {
Username = username, Username = username,
Roles = roles Roles = roles,
IssuedAt = issuedAt,
ExpiresAt = expiresAt
}; };
} }
catch { catch {
return null; return null;
} }
} }
public static string GenerateRefreshToken() { public static string GenerateRefreshToken() {
var randomNumber = new byte[32]; var randomNumber = new byte[32];
using (var rng = RandomNumberGenerator.Create()) { using (var rng = RandomNumberGenerator.Create()) {