feat: add JWT auth endpoint
This commit is contained in:
parent
af495cc032
commit
8f4eaeaa74
41
src/AccountTracking.Api/Controllers/AuthController.cs
Normal file
41
src/AccountTracking.Api/Controllers/AuthController.cs
Normal file
@ -0,0 +1,41 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using AccountTracking.Api.Models.Dtos;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace AccountTracking.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/auth")]
|
||||
public class AuthController : ControllerBase
|
||||
{
|
||||
private readonly AppCredentials _credentials;
|
||||
|
||||
public AuthController(AppCredentials credentials)
|
||||
=> _credentials = credentials;
|
||||
|
||||
[HttpPost("login")]
|
||||
public IActionResult Login([FromBody] LoginRequest request)
|
||||
{
|
||||
if (request.Username != _credentials.Username
|
||||
|| !BCrypt.Net.BCrypt.Verify(request.Password, _credentials.PasswordHash))
|
||||
return Unauthorized();
|
||||
|
||||
var expiry = DateTime.UtcNow.AddDays(30);
|
||||
var token = GenerateToken(expiry);
|
||||
|
||||
return Ok(new LoginResponse(token, expiry.ToString("O")));
|
||||
}
|
||||
|
||||
private string GenerateToken(DateTime expiry)
|
||||
{
|
||||
var key = new SymmetricSecurityKey(_credentials.JwtKeyBytes);
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
var jwt = new JwtSecurityToken(
|
||||
claims: [new Claim(ClaimTypes.Name, _credentials.Username)],
|
||||
expires: expiry,
|
||||
signingCredentials: creds);
|
||||
return new JwtSecurityTokenHandler().WriteToken(jwt);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user