using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using jsonjumble.Library; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; namespace jsonjumble.Controllers { [ApiController] [Route("jwt")] [Produces("application/json")] public class JwtAuthController : ControllerBase { private readonly ILogger Logger; private readonly IConfiguration Configuration; private readonly SHA256HashGenerator sha256HashGenerator; public JwtAuthController(ILogger logger, IConfiguration configuration) { Logger = logger; Configuration = configuration; sha256HashGenerator = Library.SHA256HashGenerator.GetInstance(); } [HttpPost] [Route("login")] public IActionResult Login([FromBody] LoginModel model) { List usersList = Configuration.GetSection("AdminUsers").Get>(); var hashedPassword = sha256HashGenerator.Get(model.Password); if (!usersList.Exists(x => x.Username.Equals(model.Username) && x.Password.Equals(hashedPassword))) { return Unauthorized(); } var authClaims = new List { new Claim(ClaimTypes.Name, model.Username), new Claim("path", model.Username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSettings:SecretKey"])); var token = new JwtSecurityToken( issuer: Configuration["JwtSettings:Issuer"], audience: Configuration["JwtSettings:Audience"], expires: DateTime.Now.AddHours(Configuration.GetValue("JwtSettings:ExpirationInHours")), claims: authClaims, signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) ); return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo }); } public class LoginModel { public string Username { get; set; } public string Password { get; set; } } } }