TokenService.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using Microsoft.AspNetCore.Identity;
  2. using Microsoft.EntityFrameworkCore;
  3. using Microsoft.IdentityModel.Tokens;
  4. using OnlineMetodist.API.Models;
  5. using System.IdentityModel.Tokens.Jwt;
  6. using System.Security.Claims;
  7. using System.Text;
  8. namespace OnlineMetodist.API.Services
  9. {
  10. public class TokenService
  11. {
  12. private const int ExpirationMinutes = 1440;
  13. private readonly ILogger<TokenService> _logger;
  14. private readonly UserManager<ApplicationUser> _userManager;
  15. public TokenService(ILogger<TokenService> logger, UserManager<ApplicationUser> userManager)
  16. {
  17. _logger = logger;
  18. _userManager = userManager;
  19. }
  20. public async Task<string> CreateTokenAsync(ApplicationUser user)
  21. {
  22. var roles = await _userManager.GetRolesAsync(user);
  23. var expiration = DateTime.UtcNow.AddMinutes(ExpirationMinutes);
  24. var token = CreateJwtToken(
  25. CreateClaims(user, roles),
  26. CreateSigningCredentials(),
  27. expiration
  28. );
  29. var tokenHandler = new JwtSecurityTokenHandler();
  30. _logger.LogInformation("JWT Token created");
  31. return tokenHandler.WriteToken(token);
  32. }
  33. private JwtSecurityToken CreateJwtToken(List<Claim> claims, SigningCredentials credentials,
  34. DateTime expiration) =>
  35. new(
  36. new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["ValidIssuer"],
  37. new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["ValidAudience"],
  38. claims,
  39. expires: expiration,
  40. signingCredentials: credentials
  41. );
  42. private List<Claim> CreateClaims(ApplicationUser user, IList<string> roles)
  43. {
  44. var jwtSub = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["JwtRegisteredClaimNamesSub"];
  45. try
  46. {
  47. var claims = new List<Claim>
  48. {
  49. new Claim(JwtRegisteredClaimNames.Sub, jwtSub),
  50. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
  51. new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()),
  52. new Claim(ClaimTypes.NameIdentifier, user.Id),
  53. new Claim(ClaimTypes.Name, user.UserName),
  54. new Claim(ClaimTypes.Email, user.Email),
  55. //для ролей тут https://dev.to/moe23/asp-net-core-rest-api-authorization-with-jwt-roles-vs-claims-vs-policy-step-by-step-5bgn
  56. };
  57. foreach (var role in roles)
  58. {
  59. claims.Add(new Claim(ClaimTypes.Role, role));
  60. }
  61. return claims;
  62. }
  63. catch (Exception e)
  64. {
  65. Console.WriteLine(e);
  66. throw;
  67. }
  68. }
  69. private SigningCredentials CreateSigningCredentials()
  70. {
  71. var symmetricSecurityKey = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("JwtTokenSettings")["SymmetricSecurityKey"];
  72. return new SigningCredentials(
  73. new SymmetricSecurityKey(
  74. Encoding.UTF8.GetBytes(symmetricSecurityKey)
  75. ),
  76. SecurityAlgorithms.HmacSha256
  77. );
  78. }
  79. }
  80. }