using System.Security.Claims; using System.Security.Cryptography; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; namespace OAuthServer.Services; public class JwtService { private readonly RSA _rsaKey; public JwtService() { _rsaKey = GetSigningKey(); } public static RSA GetSigningKey() { RSA rsaKey = RSA.Create(); const string jwtKeyPath = ".aspnet/jwt-key"; string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); string fullPath = Path.Combine(home, jwtKeyPath); if (File.Exists(fullPath)) { rsaKey.ImportRSAPrivateKey(File.ReadAllBytes(fullPath), out _); } else { string? dirName = Path.GetDirectoryName(fullPath); if (!string.IsNullOrEmpty(dirName)) Directory.CreateDirectory(dirName); var privateKey = rsaKey.ExportRSAPrivateKey(); File.WriteAllBytes(fullPath, privateKey); } return rsaKey; } public string GenerateToken(string userId, string clientId, string role, string scope) { var handler = new JsonWebTokenHandler(); var key = new RsaSecurityKey(_rsaKey); var token = handler.CreateToken(new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(JwtRegisteredClaimNames.Sub, userId), new Claim("client", clientId), new Claim("role", role), new Claim("scope", scope) }), Expires = DateTime.UtcNow.AddDays(10), SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256) }); return token; } }