Spaces:
Running
Running
| using System.IdentityModel.Tokens.Jwt; | |
| using System.Security.Claims; | |
| using System.Text; | |
| using FlowAPI.Application.Interfaces; | |
| using FlowAPI.Domain.Entities; | |
| using Microsoft.Extensions.Configuration; | |
| using Microsoft.IdentityModel.Tokens; | |
| namespace FlowAPI.Application.Services | |
| { | |
| public class TokenService : ITokenService | |
| { | |
| private readonly SymmetricSecurityKey _key; | |
| private readonly IConfiguration _config; | |
| public TokenService(IConfiguration config) | |
| { | |
| _config = config; | |
| var secretKey = _config["Jwt:Key"] ?? throw new ArgumentNullException("Jwt:Key is missing in configuration."); | |
| _key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); | |
| } | |
| public string CreateToken(User user) | |
| { | |
| var claims = new List<Claim> | |
| { | |
| new Claim(JwtRegisteredClaimNames.NameId, user.Id.ToString()), | |
| new Claim(JwtRegisteredClaimNames.Email, user.Email), | |
| new Claim("displayName", user.DisplayName) | |
| }; | |
| var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha256Signature); | |
| var tokenDescriptor = new SecurityTokenDescriptor | |
| { | |
| Subject = new ClaimsIdentity(claims), | |
| Expires = DateTime.Now.AddDays(double.Parse(_config["Jwt:ExpiryDays"] ?? "14")), | |
| SigningCredentials = creds, | |
| Issuer = _config["Jwt:Issuer"], | |
| Audience = _config["Jwt:Audience"] | |
| }; | |
| var tokenHandler = new JwtSecurityTokenHandler(); | |
| var token = tokenHandler.CreateToken(tokenDescriptor); | |
| return tokenHandler.WriteToken(token); | |
| } | |
| } | |
| } | |