Генерация JWT (JwtService)
Код: Выделить всё
public string GenerateAccessToken(User user, IEnumerable roles, IEnumerable permissions, int employeeId)
{
var secretKey = _config["Jwt:Key"] ?? "I_AM_2026";
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new List
{
new Claim(ClaimTypes.Name, user.Username),
new Claim("UserId", user.Id.ToString()),
new Claim("EmployeeId", employeeId.ToString())
};
if (roles != null && roles.Any())
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
var token = new JwtSecurityToken(
issuer: _config["Jwt:Issuer"] ?? "Backend",
audience: _config["Jwt:Audience"] ?? "Frontend",
claims: claims,
expires: DateTime.UtcNow.AddHours(8),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Код: Выделить всё
[ApiController]
[Route("api/[controller]")]
public class AttendanceController : ControllerBase
{
private int CurrentEmployeeId => int.Parse(User.FindFirst("EmployeeId")?.Value ?? "0");
protected int GetEmployeeId()
{
var claim = User.FindFirst("EmployeeId")?.Value;
return int.TryParse(claim, out int id) ? id : 0;
}
[HttpGet("daily")]
public async Task GetDaily(DateTime? date)
{
var empId = GetEmployeeId();
if (empId
[*]Есть ли лучший способ обработки пользовательских утверждений в ASP.NET Core?
[/list]
Дополнительная информация
[list]
[*]Использование веб-API ASP.NET Core
[*]Аутентификация носителя JWT
[*]Токен отправляется через авторизацию: носитель
[/list]
Будем благодарны за любую помощь.>