| 1 | using ChapterX.Application.Auth;
|
|---|
| 2 | using ChapterX.Domain.Entities;
|
|---|
| 3 | using Microsoft.Extensions.Configuration;
|
|---|
| 4 | using Microsoft.IdentityModel.Tokens;
|
|---|
| 5 | using System.IdentityModel.Tokens.Jwt;
|
|---|
| 6 | using System.Security.Claims;
|
|---|
| 7 | using System.Text;
|
|---|
| 8 |
|
|---|
| 9 | namespace ChapterX.Infrastructure.Services
|
|---|
| 10 | {
|
|---|
| 11 | public class JwtTokenService : IJwtTokenService
|
|---|
| 12 | {
|
|---|
| 13 | private readonly IConfiguration _configuration;
|
|---|
| 14 |
|
|---|
| 15 | public JwtTokenService(IConfiguration configuration)
|
|---|
| 16 | {
|
|---|
| 17 | _configuration = configuration;
|
|---|
| 18 | }
|
|---|
| 19 |
|
|---|
| 20 | public string GenerateToken(User user)
|
|---|
| 21 | {
|
|---|
| 22 | var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]!));
|
|---|
| 23 | var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|---|
| 24 |
|
|---|
| 25 | var claims = new[]
|
|---|
| 26 | {
|
|---|
| 27 | new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
|
|---|
| 28 | new Claim(JwtRegisteredClaimNames.Email, user.Email),
|
|---|
| 29 | new Claim(JwtRegisteredClaimNames.UniqueName, user.Username),
|
|---|
| 30 | new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
|---|
| 31 | };
|
|---|
| 32 |
|
|---|
| 33 | var token = new JwtSecurityToken(
|
|---|
| 34 | issuer: _configuration["Jwt:Issuer"],
|
|---|
| 35 | audience: _configuration["Jwt:Audience"],
|
|---|
| 36 | claims: claims,
|
|---|
| 37 | expires: DateTime.UtcNow.AddDays(7),
|
|---|
| 38 | signingCredentials: credentials
|
|---|
| 39 | );
|
|---|
| 40 |
|
|---|
| 41 | return new JwtSecurityTokenHandler().WriteToken(token);
|
|---|
| 42 | }
|
|---|
| 43 | }
|
|---|
| 44 | }
|
|---|