Middleware 1.0

This commit is contained in:
2025-03-11 20:23:14 +01:00
parent 3071ac7080
commit da27f7e882
6 changed files with 206 additions and 2 deletions
@@ -0,0 +1,56 @@
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace WorkFlowCheck.Web.Middleware
{
public class JwtMiddleware
{
private readonly RequestDelegate _next;
private const string _secretKey = "super_secret_key";
public JwtMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var token = context.Request.Cookies["AuthToken"];
if (!string.IsNullOrEmpty(token) && ValidateToken(token, out var claims))
{
context.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt"));
}
await _next(context);
}
private bool ValidateToken(string token, out Claim[] claims)
{
claims = null;
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_secretKey);
try
{
var principal = tokenHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
}, out var validatedToken);
claims = principal.Claims.ToArray();
return true;
}
catch
{
return false;
}
}
}
}
@@ -0,0 +1,97 @@
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,
};
// 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
};
}
}
}
}