JwtAuthController.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IdentityModel.Tokens.Jwt;
  4. using System.Security.Claims;
  5. using System.Text;
  6. using jsonjumble.Library;
  7. using Microsoft.AspNetCore.Mvc;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.Logging;
  10. using Microsoft.IdentityModel.Tokens;
  11. namespace jsonjumble.Controllers
  12. {
  13. [ApiController]
  14. [Route("jwt")]
  15. [Produces("application/json")]
  16. public class JwtAuthController : ControllerBase
  17. {
  18. private readonly ILogger<JwtAuthController> Logger;
  19. private readonly IConfiguration Configuration;
  20. private readonly SHA256HashGenerator sha256HashGenerator;
  21. public JwtAuthController(ILogger<JwtAuthController> logger, IConfiguration configuration)
  22. {
  23. Logger = logger;
  24. Configuration = configuration;
  25. sha256HashGenerator = Library.SHA256HashGenerator.GetInstance();
  26. }
  27. [HttpPost]
  28. [Route("login")]
  29. public IActionResult Login([FromBody] LoginModel model)
  30. {
  31. List<LoginModel> usersList = Configuration.GetSection("AdminUsers").Get<List<LoginModel>>();
  32. var hashedPassword = sha256HashGenerator.Get(model.Password);
  33. if (!usersList.Exists(x => x.Username.Equals(model.Username) && x.Password.Equals(hashedPassword)))
  34. {
  35. return Unauthorized();
  36. }
  37. var authClaims = new List<Claim>
  38. {
  39. new Claim(ClaimTypes.Name, model.Username),
  40. new Claim("path", model.Username),
  41. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
  42. };
  43. var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSettings:SecretKey"]));
  44. var token = new JwtSecurityToken(
  45. issuer: Configuration["JwtSettings:Issuer"],
  46. audience: Configuration["JwtSettings:Audience"],
  47. expires: DateTime.Now.AddHours(Configuration.GetValue<int>("JwtSettings:ExpirationInHours")),
  48. claims: authClaims,
  49. signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
  50. );
  51. return Ok(new
  52. {
  53. token = new JwtSecurityTokenHandler().WriteToken(token),
  54. expiration = token.ValidTo
  55. });
  56. }
  57. public class LoginModel
  58. {
  59. public string Username { get; set; }
  60. public string Password { get; set; }
  61. }
  62. }
  63. }