Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

AuthenticationService.cs 3.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using Diligent.WebAPI.Business.Interfaces;
  2. using Diligent.WebAPI.Data.Entities;
  3. using Microsoft.AspNetCore.Identity;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.IdentityModel.Tokens;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IdentityModel.Tokens.Jwt;
  9. using System.Linq;
  10. using System.Security.Claims;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace Diligent.WebAPI.Business.Services
  14. {
  15. public class AuthenticationService:IAuthenticationService
  16. {
  17. private readonly UserManager<Customer> _customerManager;
  18. private readonly IConfiguration _configuration;
  19. private Customer _customer;
  20. public AuthenticationService(UserManager<Customer> customerManager,IConfiguration configuration)
  21. {
  22. _customerManager = customerManager;
  23. _configuration = configuration;
  24. }
  25. public async Task<bool> ValidateCustomer(string username,string password)
  26. {
  27. _customer = await _customerManager.FindByNameAsync(username);
  28. return (_customer != null && await _customerManager.CheckPasswordAsync
  29. (_customer, password));
  30. }
  31. public async Task<string?> GenerateToken()
  32. {
  33. if (_customer == null) return null;
  34. var signingCredentials = GetSigningCredentials();
  35. var claims = await GetClaims();
  36. var tokenOptions = GenerateTokenOptions(signingCredentials, claims);
  37. // return created token as string
  38. return new JwtSecurityTokenHandler().WriteToken(tokenOptions);
  39. }
  40. private async Task<List<Claim>> GetClaims()
  41. {
  42. //method creates a list of claims with the user name inside and all the roles the user belongs to.
  43. Claim claim = new (ClaimTypes.Name, _customer.UserName);
  44. var claims = new List<Claim>
  45. {
  46. claim
  47. };
  48. IList<string> roles = await _customerManager.GetRolesAsync(_customer);
  49. foreach (var role in roles)
  50. {
  51. claims.Add(new Claim(ClaimTypes.Role, role));
  52. }
  53. return claims;
  54. }
  55. private SigningCredentials GetSigningCredentials()
  56. {
  57. // This method returns secret key as a byte array with the security algorithm
  58. var jwtSettings = _configuration.GetSection("JwtSettings");
  59. var key = Encoding.UTF8.GetBytes(jwtSettings["jwtSecret"]);
  60. var secret = new SymmetricSecurityKey(key);
  61. return new SigningCredentials(secret, SecurityAlgorithms.HmacSha256);
  62. }
  63. private JwtSecurityToken GenerateTokenOptions(SigningCredentials
  64. signingCredentials, List<Claim> claims)
  65. {
  66. //return an object of the JwtSecurityToken type with all of the required options
  67. var jwtSettings = _configuration.GetSection("JwtSettings");
  68. var tokenOptions = new JwtSecurityToken
  69. (
  70. issuer: jwtSettings.GetSection("validIssuer").Value,
  71. audience: jwtSettings.GetSection("validAudience").Value,
  72. claims: claims,
  73. expires: DateTime.Now.AddDays(7),
  74. signingCredentials: signingCredentials
  75. );
  76. return tokenOptions;
  77. }
  78. }
  79. }