From 9d0a577c1ffc2e2d9c6fa783e1178d08e9114ddf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20Szab=C3=B3?= Date: Fri, 14 Mar 2025 10:25:08 +0100 Subject: [PATCH] =?UTF-8?q?Ment=C3=A9s=20+=20JwtMiddleware-b=C5=91l=20a=20?= =?UTF-8?q?dolgok=20berakva?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Middleware/JwtMiddleware.cs | 2 +- .../Middleware/JwtService.cs | 99 ------------------- .../CheckPoints/CheckPointEditPage.cshtml | 7 +- .../CheckPoints/CheckPointEditPage.cshtml.cs | 10 +- src/WorkFlowCheck.Web/Program.cs | 2 +- src/WorkFlowCheck.Web/Services/BaseService.cs | 14 ++- .../Services/BaseStockService.cs | 33 ++++++- .../Services/Interfaces/IBaseStockService.cs | 2 +- src/WorkFlowCheck.Web/Services/UserService.cs | 2 +- 9 files changed, 54 insertions(+), 117 deletions(-) delete mode 100644 src/WorkFlowCheck.Web/Middleware/JwtService.cs diff --git a/src/WorkFlowCheck.Web/Middleware/JwtMiddleware.cs b/src/WorkFlowCheck.Web/Middleware/JwtMiddleware.cs index 6724ebc..3dec41d 100644 --- a/src/WorkFlowCheck.Web/Middleware/JwtMiddleware.cs +++ b/src/WorkFlowCheck.Web/Middleware/JwtMiddleware.cs @@ -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; diff --git a/src/WorkFlowCheck.Web/Middleware/JwtService.cs b/src/WorkFlowCheck.Web/Middleware/JwtService.cs deleted file mode 100644 index 69f45cb..0000000 --- a/src/WorkFlowCheck.Web/Middleware/JwtService.cs +++ /dev/null @@ -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 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> 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() - }; - - // 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>(jsonString); - - return response ?? new ApiResponseDTO - { - IsSuccess = false, - }; - } - } - catch (Exception ex) - { - // Hiba visszaadása - return new ApiResponseDTO - { - IsSuccess = false - }; - } - } - - } -} diff --git a/src/WorkFlowCheck.Web/Pages/BaseStock/CheckPoints/CheckPointEditPage.cshtml b/src/WorkFlowCheck.Web/Pages/BaseStock/CheckPoints/CheckPointEditPage.cshtml index ae1d20a..f1fb0db 100644 --- a/src/WorkFlowCheck.Web/Pages/BaseStock/CheckPoints/CheckPointEditPage.cshtml +++ b/src/WorkFlowCheck.Web/Pages/BaseStock/CheckPoints/CheckPointEditPage.cshtml @@ -16,9 +16,7 @@
- - - +
@@ -108,9 +106,6 @@ $("#saveCheckPoint").click(function () { const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content'); var formData = getFormAsNestedObject('#checkPointForm'); - - console.log(formData); - console.log(JSON.stringify(formData.CheckPoint)); $.ajax({ url: $('#checkPointEditPostUrl').val(), diff --git a/src/WorkFlowCheck.Web/Pages/BaseStock/CheckPoints/CheckPointEditPage.cshtml.cs b/src/WorkFlowCheck.Web/Pages/BaseStock/CheckPoints/CheckPointEditPage.cshtml.cs index a81a42c..f27554f 100644 --- a/src/WorkFlowCheck.Web/Pages/BaseStock/CheckPoints/CheckPointEditPage.cshtml.cs +++ b/src/WorkFlowCheck.Web/Pages/BaseStock/CheckPoints/CheckPointEditPage.cshtml.cs @@ -35,11 +35,17 @@ namespace WorkFlowCheck.Web.Pages.BaseStock.CheckPoints public async Task OnPostSave([FromBody] CheckPointDTO checkPointDTO) { - try { var result = await _baseStockService.UpdateCheckPoint(checkPointDTO); - return new JsonResult(new { success = true }); + if (result.IsSuccess) + { + return new JsonResult(new { success = true }); + } + else + { + return new JsonResult(new { success = false }); + } } catch (Exception ex) { diff --git a/src/WorkFlowCheck.Web/Program.cs b/src/WorkFlowCheck.Web/Program.cs index ff24eee..150db7a 100644 --- a/src/WorkFlowCheck.Web/Program.cs +++ b/src/WorkFlowCheck.Web/Program.cs @@ -25,7 +25,7 @@ builder.Services.AddScoped(); builder.Host.UseSerilog(); // Add services to the container. builder.Services.AddRazorPages(); -builder.Services.AddSingleton(); + builder.Services.AddAntiforgery(options => { options.HeaderName = "X-CSRF-TOKEN"; // JS API hívásokhoz diff --git a/src/WorkFlowCheck.Web/Services/BaseService.cs b/src/WorkFlowCheck.Web/Services/BaseService.cs index d1e75d5..99397ad 100644 --- a/src/WorkFlowCheck.Web/Services/BaseService.cs +++ b/src/WorkFlowCheck.Web/Services/BaseService.cs @@ -1,23 +1,33 @@  +using System.Net.Http.Headers; + namespace WorkFlowCheck.Web.Services { public class BaseService { + private readonly IHttpContextAccessor _httpContextAccessor; public readonly HttpClient _httpClient; public readonly IConfiguration _configuration; - - public BaseService(HttpClient httpClient, IConfiguration configuration) + + public BaseService(HttpClient httpClient, IConfiguration configuration, IHttpContextAccessor httpContextAccessor) { _httpClient = httpClient; _configuration = configuration; + _httpContextAccessor = httpContextAccessor; var apiBaseUrl = configuration["ApiBaseUrl"]; // API-cím elérése a konfigurációból _httpClient.BaseAddress = new Uri(apiBaseUrl); var apiKey = configuration["ApiKey"]; _httpClient.DefaultRequestHeaders.Add("X-Api-Key", apiKey); + + var jwtToken = _httpContextAccessor.HttpContext?.Request.Cookies["AuthToken"]; + if (!string.IsNullOrEmpty(jwtToken)) + { + _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); + } } } } diff --git a/src/WorkFlowCheck.Web/Services/BaseStockService.cs b/src/WorkFlowCheck.Web/Services/BaseStockService.cs index 9a123da..44e567d 100644 --- a/src/WorkFlowCheck.Web/Services/BaseStockService.cs +++ b/src/WorkFlowCheck.Web/Services/BaseStockService.cs @@ -1,4 +1,5 @@ -using Serilog; +using Newtonsoft.Json; +using Serilog; using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Web.Services.Interfaces; @@ -6,7 +7,7 @@ namespace WorkFlowCheck.Web.Services { public class BaseStockService : BaseService, IBaseStockService { - public BaseStockService(HttpClient httpClient, IConfiguration configuration) : base(httpClient, configuration) + public BaseStockService(HttpClient httpClient, IConfiguration configuration, IHttpContextAccessor httpContextAccessor) : base(httpClient, configuration, httpContextAccessor) { } @@ -55,9 +56,33 @@ namespace WorkFlowCheck.Web.Services return retVal; } - public async Task UpdateCheckPoint(CheckPointDTO checkPointDto) + public async Task> UpdateCheckPoint(CheckPointDTO checkPointDTO) { - return null; + try + { + string endpoint = $"{_httpClient.BaseAddress}api/sync/updatecheckpoint"; + + using (HttpResponseMessage httpResponseMessage = await _httpClient.PostAsJsonAsync(endpoint, checkPointDTO)) + { + httpResponseMessage.EnsureSuccessStatusCode(); + + var jsonString = await httpResponseMessage.Content.ReadAsStringAsync(); + var response = JsonConvert.DeserializeObject>(jsonString); + + return response ?? new ApiResponseDTO + { + IsSuccess = false, + }; + } + } + catch (Exception ex) + { + // Hiba visszaadása + return new ApiResponseDTO + { + IsSuccess = false + }; + } } } diff --git a/src/WorkFlowCheck.Web/Services/Interfaces/IBaseStockService.cs b/src/WorkFlowCheck.Web/Services/Interfaces/IBaseStockService.cs index 93a5a8f..8f14ce8 100644 --- a/src/WorkFlowCheck.Web/Services/Interfaces/IBaseStockService.cs +++ b/src/WorkFlowCheck.Web/Services/Interfaces/IBaseStockService.cs @@ -6,6 +6,6 @@ namespace WorkFlowCheck.Web.Services.Interfaces { Task> GetAllCheckPoints(); Task GetCheckPoint(int id); - Task UpdateCheckPoint(CheckPointDTO checkPoint); + Task> UpdateCheckPoint(CheckPointDTO checkPoint); } } diff --git a/src/WorkFlowCheck.Web/Services/UserService.cs b/src/WorkFlowCheck.Web/Services/UserService.cs index 1321f27..5db51eb 100644 --- a/src/WorkFlowCheck.Web/Services/UserService.cs +++ b/src/WorkFlowCheck.Web/Services/UserService.cs @@ -7,7 +7,7 @@ namespace WorkFlowCheck.Web.Services { public class UserService : BaseService, IUserService { - public UserService(HttpClient httpClient, IConfiguration configuration) : base(httpClient, configuration) + public UserService(HttpClient httpClient, IConfiguration configuration, IHttpContextAccessor httpContextAccessor) : base(httpClient, configuration, httpContextAccessor) { } public async Task> Authenticate(string username, string password)