Mentés + JwtMiddleware-ből a dolgok berakva

This commit is contained in:
2025-03-14 10:25:08 +01:00
parent ca789cfbc3
commit 9d0a577c1f
9 changed files with 54 additions and 117 deletions
@@ -11,7 +11,7 @@ namespace WorkFlowCheck.Web.Middleware
private readonly RequestDelegate _next;
public readonly IConfiguration _configuration;
public JwtMiddleware(RequestDelegate next,IConfiguration configuration)
public JwtMiddleware(RequestDelegate next, IConfiguration configuration)
{
_next = next;
_configuration = configuration;
@@ -1,99 +0,0 @@
using Microsoft.AspNetCore.Identity.Data;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.Web.Middleware
{
public class JwtService
{
private const string SecretKey = "super_secret_key";
public readonly IConfiguration _configuration;
private readonly HttpClient _httpClient;
public JwtService(HttpClient httpClient, IConfiguration configuration)
{
_configuration = configuration;
_httpClient = httpClient;
}
public async Task<string?> AuthenticateUserAsync(UserDTO userDTO)
{
var jwtSettings = _configuration.GetSection("Jwt");
var secretKey = jwtSettings["SecretKey"];
var issuer = jwtSettings["Issuer"];
var audience = jwtSettings["Audience"];
var tokenLifetime = int.Parse(jwtSettings["TokenLifetimeMinutes"]);
var response = await Authenticate(userDTO.UserName, userDTO.Password);
if (response != null && response.IsSuccess)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, userDTO.UserName),
new Claim(ClaimTypes.Role, "User")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(tokenLifetime),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
return null;
}
private async Task<ApiResponseDTO<UserDTO>> Authenticate(string username, string password)
{
try
{
// Az API végpont meghatározása
string endpoint = $"{_httpClient.BaseAddress}api/user/authenticate";
var userDTO = new UserDTO()
{
Email = "",
FirstName = "",
LastName = "",
Id = 0,
UserName = username,
Password = password,
RoleDTO = new List<RoleDTO>()
};
// HTTP POST kérés küldése
using (HttpResponseMessage httpResponseMessage = await _httpClient.PostAsJsonAsync(endpoint, userDTO))
{
httpResponseMessage.EnsureSuccessStatusCode();
var jsonString = await httpResponseMessage.Content.ReadAsStringAsync();
var response = JsonConvert.DeserializeObject<ApiResponseDTO<UserDTO>>(jsonString);
return response ?? new ApiResponseDTO<UserDTO>
{
IsSuccess = false,
};
}
}
catch (Exception ex)
{
// Hiba visszaadása
return new ApiResponseDTO<UserDTO>
{
IsSuccess = false
};
}
}
}
}