0
0
RhSolutions-Api/RhSolutions.Api/Controllers/AccountController.cs
Serghei Cebotari e9e34c5fec
All checks were successful
Test and release / test (push) Successful in 1m44s
Test and release / release-image (push) Successful in 3m51s
Implement JWT tokens
2024-02-07 16:32:34 +03:00

72 lines
2.1 KiB
C#

using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
namespace RhSolutions.Api.Controllers;
[ApiController]
[Route("/api/account")]
public class AccountController : ControllerBase
{
private SignInManager<IdentityUser> _signInManager;
private UserManager<IdentityUser> _userManager;
private IConfiguration _configuration;
public AccountController(SignInManager<IdentityUser> signInManager,
UserManager<IdentityUser> userManager,
IConfiguration configuration)
{
_signInManager = signInManager;
_userManager = userManager;
_configuration = configuration;
}
/// <summary>
/// Получение токена
/// </summary>
/// <param name="credentials"></param>
/// <returns></returns>
[HttpPost("token")]
public async Task<IActionResult> Token([FromBody] Credentials credentials)
{
if (await CheckPassword(credentials))
{
JwtSecurityTokenHandler handler = new();
string jwtSecret = _configuration["JWT_SECRET"] ?? "mold-smartness-arrive-overstate-aspirin";
byte[] secret = Encoding.ASCII.GetBytes(jwtSecret);
SecurityTokenDescriptor descriptor = new()
{
Subject = new ClaimsIdentity(new Claim[]
{
new (ClaimTypes.Name, credentials.Username)
}),
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = new(new SymmetricSecurityKey(secret), SecurityAlgorithms.HmacSha256Signature)
};
SecurityToken token = handler.CreateToken(descriptor);
return Ok(new
{
Success = true,
Token = handler.WriteToken(token)
});
}
return Unauthorized();
}
private async Task<bool> CheckPassword(Credentials credentials)
{
IdentityUser? user = await _userManager.FindByNameAsync(credentials.Username);
if (user != null)
{
return (await _signInManager.CheckPasswordSignInAsync(user, credentials.Password, true)).Succeeded;
}
return false;
}
public class Credentials
{
public string Username { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
}
}