AuthService.cs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using Microsoft.AspNetCore.Identity;
  2. using Microsoft.Extensions.Options;
  3. using Microsoft.IdentityModel.Tokens;
  4. using MTWorkHR.Application.Exceptions;
  5. using MTWorkHR.Application.Identity;
  6. using MTWorkHR.Application.Models;
  7. using MTWorkHR.Core.Global;
  8. using MTWorkHR.Identity.Entities;
  9. using System.IdentityModel.Tokens.Jwt;
  10. using System.Security.Claims;
  11. using System.Text;
  12. namespace MTWorkHR.Identity.Services
  13. {
  14. public class AuthService : IAuthService
  15. {
  16. private readonly UserManager<ApplicationUser> _userManager;
  17. private readonly SignInManager<ApplicationUser> _signInManager;
  18. private readonly AppSettingsConfiguration _configuration;
  19. public AuthService(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, AppSettingsConfiguration configuration)
  20. {
  21. _userManager = userManager;
  22. _signInManager = signInManager;
  23. _configuration = configuration;
  24. }
  25. public async Task<AuthResponse> Login(AuthRequest request)
  26. {
  27. var user = await _userManager.FindByEmailAsync(request.Email);
  28. if(user == null)
  29. {
  30. throw new NotFoundException($"User with {request.Email} not found", request.Email);
  31. }
  32. var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
  33. if(!result.Succeeded)
  34. {
  35. throw new BadRequest($"Credentials for '{request.Email} are not valid'.");
  36. }
  37. JwtSecurityToken jwtToken = await GenerateToken(user);
  38. var response = new AuthResponse
  39. {
  40. Id = user.Id,
  41. Email = user.Email,
  42. UserName = user.UserName,
  43. Token = new JwtSecurityTokenHandler().WriteToken( jwtToken),
  44. Expiration = jwtToken.ValidTo
  45. };
  46. return response;
  47. }
  48. //public async Task<RegistrationResponse> Register(RegistrationRequest request)
  49. //{
  50. // var user = new ApplicationUser {
  51. // Email = request.Email ,
  52. // UserName = request.UserName ,
  53. // FirstName = request.FirstName ,
  54. // LastName = request.LastName ,
  55. // EmailConfirmed = true
  56. // };
  57. // var result = await _userManager.CreateAsync(user, request.Password);
  58. // if (result.Succeeded)
  59. // {
  60. // await _userManager.AddToRoleAsync(user, request.RoleName);
  61. // return new RegistrationResponse(){ UserId = user.Id };
  62. // }
  63. // else
  64. // {
  65. // StringBuilder str = new StringBuilder();
  66. // foreach (var err in result.Errors)
  67. // {
  68. // str.AppendFormat(".{0}\n", err.Description);
  69. // }
  70. // throw new BadRequest($"{str}");
  71. // }
  72. //}
  73. private async Task<JwtSecurityToken> GenerateToken(ApplicationUser user)
  74. {
  75. var userCalims = await _userManager.GetClaimsAsync(user);
  76. var roles = await _userManager.GetRolesAsync(user);
  77. var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role, r)).ToList();
  78. var claims = new[]
  79. {
  80. new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
  81. new Claim(JwtRegisteredClaimNames.Email, user.Email),
  82. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
  83. new Claim("uid", user.Id)
  84. }.Union(userCalims)
  85. .Union(roleClaims);
  86. var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.JwtSettings.SecretKey));
  87. var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
  88. var jwtSecurityToken = new JwtSecurityToken(
  89. issuer: _configuration.JwtSettings.Issuer,
  90. audience: _configuration.JwtSettings.Audience,
  91. claims: claims,
  92. expires: DateTime.Now.AddMinutes(_configuration.JwtSettings.DurationInMinutes),
  93. signingCredentials: signingCredentials
  94. );
  95. return jwtSecurityToken;
  96. }
  97. }
  98. }