using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using OnlineMetodist.API.Models; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace OnlineMetodist.API.Services { public class TokenService { private const int ExpirationMinutes = 1440; private readonly ILogger _logger; private readonly UserManager _userManager; public TokenService(ILogger logger, UserManager userManager) { _logger = logger; _userManager = userManager; } public async Task CreateTokenAsync(ApplicationUser user) { var roles = await _userManager.GetRolesAsync(user); var expiration = DateTime.UtcNow.AddMinutes(ExpirationMinutes); var token = CreateJwtToken( CreateClaims(user, roles), CreateSigningCredentials(), expiration ); var tokenHandler = new JwtSecurityTokenHandler(); _logger.LogInformation("JWT Token created"); return tokenHandler.WriteToken(token); } private JwtSecurityToken CreateJwtToken(List claims, SigningCredentials credentials, DateTime expiration) => new( new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["ValidIssuer"], new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["ValidAudience"], claims, expires: expiration, signingCredentials: credentials ); private List CreateClaims(ApplicationUser user, IList roles) { var jwtSub = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["JwtRegisteredClaimNamesSub"]; try { var claims = new List { new Claim(JwtRegisteredClaimNames.Sub, jwtSub), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()), new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Email, user.Email), //для ролей тут https://dev.to/moe23/asp-net-core-rest-api-authorization-with-jwt-roles-vs-claims-vs-policy-step-by-step-5bgn }; foreach (var role in roles) { claims.Add(new Claim(ClaimTypes.Role, role)); } return claims; } catch (Exception e) { Console.WriteLine(e); throw; } } private SigningCredentials CreateSigningCredentials() { var symmetricSecurityKey = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["SymmetricSecurityKey"]; return new SigningCredentials( new SymmetricSecurityKey( Encoding.UTF8.GetBytes(symmetricSecurityKey) ), SecurityAlgorithms.HmacSha256 ); } } }