using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using Microsoft.IdentityModel.Tokens; using USEntryCoach.Server.Data; namespace USEntryCoach.Server.Services; public class TokenService { private byte[] _secretToken; private double _jwtExpiryMinutes; private const double DefaultJwtExpiryMinutes = 15; public TokenService(IConfiguration configuration) { string? secretToken = configuration.GetValue("Authentication:Secret"); if (secretToken == null) { throw new Exception("No Authentication Secret Token set! Please define a value for \"Authentication:SecretToken\" in appsettings.json."); } _secretToken = Encoding.ASCII.GetBytes(secretToken); double? jwtExpiryMinutes = configuration.GetValue("Authentication:JwtExpiryMinutes"); if (jwtExpiryMinutes == null) { // TODO: Use logger Console.WriteLine($"Warning: No expiry time for jwt session tokens defined. Using {DefaultJwtExpiryMinutes} minutes."); } _jwtExpiryMinutes = jwtExpiryMinutes ?? DefaultJwtExpiryMinutes; } public string GenerateToken(User user) { JwtSecurityTokenHandler tokenHandler = new(); SecurityTokenDescriptor tokenDescriptor = new() { Subject = new ClaimsIdentity([ new Claim(ClaimTypes.Name, user.Username), //new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Role, user.Role.ToString()) ]), Expires = DateTime.UtcNow.AddMinutes(_jwtExpiryMinutes), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(_secretToken), SecurityAlgorithms.HmacSha256Signature) }; SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } }