1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- 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<JwtAuthController> Logger;
- private readonly IConfiguration Configuration;
- private readonly SHA256HashGenerator sha256HashGenerator;
- public JwtAuthController(ILogger<JwtAuthController> logger, IConfiguration configuration)
- {
- Logger = logger;
- Configuration = configuration;
- sha256HashGenerator = Library.SHA256HashGenerator.GetInstance();
- }
- [HttpPost]
- [Route("login")]
- public IActionResult Login([FromBody] LoginModel model)
- {
- List<LoginModel> usersList = Configuration.GetSection("AdminUsers").Get<List<LoginModel>>();
- 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<Claim>
- {
- 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<int>("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; }
- }
- }
- }
|