12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- 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<TokenService> _logger;
- private readonly UserManager<ApplicationUser> _userManager;
- public TokenService(ILogger<TokenService> logger, UserManager<ApplicationUser> userManager)
- {
- _logger = logger;
- _userManager = userManager;
- }
- public async Task<string> 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<Claim> 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<Claim> CreateClaims(ApplicationUser user, IList<string> roles)
- {
- var jwtSub = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["JwtRegisteredClaimNamesSub"];
- try
- {
- var claims = new List<Claim>
- {
- 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
- );
- }
- }
- }
|