AuthService.cs 4.3 KB

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