From 72dd365ffeebbd6c01e0519b34160f54d5cea76d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9E=D0=BB=D1=8F=20=D0=91=D0=B8=D0=B7=D1=8E=D0=BA=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0?= Date: Fri, 31 Jan 2025 16:07:17 +0500 Subject: [PATCH 1/4] =?UTF-8?q?=D0=A3=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20restsharp=20=D0=B8=20=D0=B8=D1=81=D0=BF=D0=BE=D0=BB?= =?UTF-8?q?=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=BE=D0=B1?= =?UTF-8?q?=D1=8B=D1=87=D0=BD=D0=BE=D0=B3=D0=BE=20httpClient?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DD.Persistence.Client.csproj | 1 - .../Helpers/ApiTokenHelper.cs | 79 +++++++++++-------- .../TestHttpClientFactory.cs | 2 +- .../WebAppFactoryFixture.cs | 1 - 4 files changed, 49 insertions(+), 34 deletions(-) diff --git a/DD.Persistence.Client/DD.Persistence.Client.csproj b/DD.Persistence.Client/DD.Persistence.Client.csproj index 5d60611..2395482 100644 --- a/DD.Persistence.Client/DD.Persistence.Client.csproj +++ b/DD.Persistence.Client/DD.Persistence.Client.csproj @@ -52,7 +52,6 @@ - diff --git a/DD.Persistence.Client/Helpers/ApiTokenHelper.cs b/DD.Persistence.Client/Helpers/ApiTokenHelper.cs index 9e62110..85fa428 100644 --- a/DD.Persistence.Client/Helpers/ApiTokenHelper.cs +++ b/DD.Persistence.Client/Helpers/ApiTokenHelper.cs @@ -1,16 +1,25 @@ +using DD.Persistence.Models.Configurations; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; -using DD.Persistence.Models.Configurations; -using RestSharp; using System.IdentityModel.Tokens.Jwt; using System.Net.Http.Headers; using System.Security.Claims; using System.Text.Json; namespace DD.Persistence.Client.Helpers; + +/// +/// Класс, позволяющий генерировать api-token +/// public static class ApiTokenHelper { - public static void Authorize(this HttpClient httpClient, IConfiguration configuration) + /// + /// Метод авториации + /// + /// + /// + /// + public static async Task Authorize(this HttpClient httpClient, IConfiguration configuration) { var authUser = configuration .GetSection(nameof(AuthUser)) @@ -21,29 +30,29 @@ public static class ApiTokenHelper var keycloakGetTokenUrl = configuration.GetSection("KeycloakGetTokenUrl").Get() ?? string.Empty; var jwtToken = needUseKeyCloak - ? authUser.CreateKeyCloakJwtToken(keycloakGetTokenUrl) + ? await authUser.CreateKeyCloakJwtToken(keycloakGetTokenUrl) : authUser.CreateDefaultJwtToken(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); } - public static void Authorize(this HttpClient httpClient, string jwtToken) - { - httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); - } - + /// + /// Авторизация через собственный jwt-токен + /// + /// + /// private static string CreateDefaultJwtToken(this AuthUser authUser) - { - var nameIdetifier = Guid.NewGuid().ToString(); - var claims = new List() - { - new(ClaimTypes.NameIdentifier, nameIdetifier), - new("client_id", authUser.ClientId), - new("username", authUser.Username), - new("password", authUser.Password), - new("grant_type", authUser.GrantType), - new(ClaimTypes.NameIdentifier.ToString(), Guid.NewGuid().ToString()) - }; + { + var nameIdetifier = Guid.NewGuid().ToString(); + var claims = new List() + { + new(ClaimTypes.NameIdentifier, nameIdetifier), + new("client_id", authUser.ClientId), + new("username", authUser.Username), + new("password", authUser.Password), + new("grant_type", authUser.GrantType), + new(ClaimTypes.NameIdentifier.ToString(), Guid.NewGuid().ToString()) + }; var tokenDescriptor = new SecurityTokenDescriptor { @@ -58,23 +67,31 @@ public static class ApiTokenHelper return tokenHandler.WriteToken(token); } - private static string CreateKeyCloakJwtToken(this AuthUser authUser, string keycloakGetTokenUrl) + /// + /// Авторизация через jwt-токен keycloak + /// + /// + /// + /// + private static async Task CreateKeyCloakJwtToken(this AuthUser authUser, string keycloakGetTokenUrl) { - var restClient = new RestClient(); + var sharedClient = new HttpClient(); + var parameters = new Dictionary { + { "username", authUser.Username }, + { "password", authUser.Password }, + { "client_id", authUser.ClientId }, + { "grant_type", authUser.GrantType }, + }; + var encodedContent = new FormUrlEncodedContent(parameters); - var request = new RestRequest(keycloakGetTokenUrl, Method.Post); - request.AddParameter("username", authUser.Username); - request.AddParameter("password", authUser.Password); - request.AddParameter("client_id", authUser.ClientId); - request.AddParameter("grant_type", authUser.GrantType); + using HttpResponseMessage response = await sharedClient.PostAsync(keycloakGetTokenUrl, encodedContent); - var keycloakResponse = restClient.Post(request); - if (keycloakResponse.IsSuccessful && !String.IsNullOrEmpty(keycloakResponse.Content)) + if (response.IsSuccessStatusCode == true) { - var token = JsonSerializer.Deserialize(keycloakResponse.Content)!; + var data = await response.Content.ReadAsStreamAsync(); + var token = JsonSerializer.Deserialize(data)!; return token.AccessToken; } - return String.Empty; } } diff --git a/DD.Persistence.IntegrationTests/TestHttpClientFactory.cs b/DD.Persistence.IntegrationTests/TestHttpClientFactory.cs index 51b8783..4c0cd04 100644 --- a/DD.Persistence.IntegrationTests/TestHttpClientFactory.cs +++ b/DD.Persistence.IntegrationTests/TestHttpClientFactory.cs @@ -19,7 +19,7 @@ namespace DD.Persistence.IntegrationTests public HttpClient CreateClient(string name) { var client = factory.CreateClient(); - client.Authorize(configuration); + client.Authorize(configuration).GetAwaiter().GetResult(); return client; } diff --git a/DD.Persistence.IntegrationTests/WebAppFactoryFixture.cs b/DD.Persistence.IntegrationTests/WebAppFactoryFixture.cs index 31b4da4..435287a 100644 --- a/DD.Persistence.IntegrationTests/WebAppFactoryFixture.cs +++ b/DD.Persistence.IntegrationTests/WebAppFactoryFixture.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.Logging; using DD.Persistence.API; using DD.Persistence.Client; using DD.Persistence.Database.Model; -using RestSharp; using DD.Persistence.App; using DD.Persistence.Client.Helpers; using DD.Persistence.Factories; -- 2.45.2 From b129f22b739abd2c034d4a9bd8e3474272d359e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9E=D0=BB=D1=8F=20=D0=91=D0=B8=D0=B7=D1=8E=D0=BA=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0?= Date: Fri, 31 Jan 2025 17:04:05 +0500 Subject: [PATCH 2/4] =?UTF-8?q?=D0=BC=D0=B8=D0=BD=D0=B8-=D1=80=D0=B5=D1=84?= =?UTF-8?q?=D0=B0=D0=BA=D1=82=D0=BE=D1=80=D0=B8=D0=BD=D0=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DD.Persistence.Client/Helpers/ApiTokenHelper.cs | 10 +++++----- .../TestHttpClientFactory.cs | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/DD.Persistence.Client/Helpers/ApiTokenHelper.cs b/DD.Persistence.Client/Helpers/ApiTokenHelper.cs index 85fa428..4a46016 100644 --- a/DD.Persistence.Client/Helpers/ApiTokenHelper.cs +++ b/DD.Persistence.Client/Helpers/ApiTokenHelper.cs @@ -19,7 +19,7 @@ public static class ApiTokenHelper /// /// /// - public static async Task Authorize(this HttpClient httpClient, IConfiguration configuration) + public static void Authorize(this HttpClient httpClient, IConfiguration configuration) { var authUser = configuration .GetSection(nameof(AuthUser)) @@ -30,7 +30,7 @@ public static class ApiTokenHelper var keycloakGetTokenUrl = configuration.GetSection("KeycloakGetTokenUrl").Get() ?? string.Empty; var jwtToken = needUseKeyCloak - ? await authUser.CreateKeyCloakJwtToken(keycloakGetTokenUrl) + ? authUser.CreateKeyCloakJwtToken(keycloakGetTokenUrl) : authUser.CreateDefaultJwtToken(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); @@ -73,7 +73,7 @@ public static class ApiTokenHelper /// /// /// - private static async Task CreateKeyCloakJwtToken(this AuthUser authUser, string keycloakGetTokenUrl) + private static string CreateKeyCloakJwtToken(this AuthUser authUser, string keycloakGetTokenUrl) { var sharedClient = new HttpClient(); var parameters = new Dictionary { @@ -84,11 +84,11 @@ public static class ApiTokenHelper }; var encodedContent = new FormUrlEncodedContent(parameters); - using HttpResponseMessage response = await sharedClient.PostAsync(keycloakGetTokenUrl, encodedContent); + using HttpResponseMessage response = sharedClient.PostAsync(keycloakGetTokenUrl, encodedContent).GetAwaiter().GetResult(); if (response.IsSuccessStatusCode == true) { - var data = await response.Content.ReadAsStreamAsync(); + var data = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); var token = JsonSerializer.Deserialize(data)!; return token.AccessToken; } diff --git a/DD.Persistence.IntegrationTests/TestHttpClientFactory.cs b/DD.Persistence.IntegrationTests/TestHttpClientFactory.cs index 4c0cd04..51b8783 100644 --- a/DD.Persistence.IntegrationTests/TestHttpClientFactory.cs +++ b/DD.Persistence.IntegrationTests/TestHttpClientFactory.cs @@ -19,7 +19,7 @@ namespace DD.Persistence.IntegrationTests public HttpClient CreateClient(string name) { var client = factory.CreateClient(); - client.Authorize(configuration).GetAwaiter().GetResult(); + client.Authorize(configuration); return client; } -- 2.45.2 From 9659b7bc8c3c6b7ff42d48a1d3ba63ea5dc32d79 Mon Sep 17 00:00:00 2001 From: Olga Nemt Date: Mon, 3 Feb 2025 09:53:13 +0500 Subject: [PATCH 3/4] =?UTF-8?q?=D0=9A=D0=BE=D0=B4=D0=B8=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DD.Persistence.Client/Helpers/ApiTokenHelper.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/DD.Persistence.Client/Helpers/ApiTokenHelper.cs b/DD.Persistence.Client/Helpers/ApiTokenHelper.cs index 4a46016..3487dcb 100644 --- a/DD.Persistence.Client/Helpers/ApiTokenHelper.cs +++ b/DD.Persistence.Client/Helpers/ApiTokenHelper.cs @@ -9,12 +9,12 @@ using System.Text.Json; namespace DD.Persistence.Client.Helpers; /// -/// Класс, позволяющий генерировать api-token +///  Класс, позволяющий генерировать api-token /// public static class ApiTokenHelper { /// - /// Метод авториации + /// Метод авторизации /// /// /// @@ -30,14 +30,14 @@ public static class ApiTokenHelper var keycloakGetTokenUrl = configuration.GetSection("KeycloakGetTokenUrl").Get() ?? string.Empty; var jwtToken = needUseKeyCloak - ? authUser.CreateKeyCloakJwtToken(keycloakGetTokenUrl) + ? authUser.CreateKeyCloakJwtToken(keycloakGetTokenUrl, httpClient) : authUser.CreateDefaultJwtToken(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); } /// - /// Авторизация через собственный jwt-токен + /// Авторизация через собственный jwt-токен /// /// /// @@ -68,14 +68,13 @@ public static class ApiTokenHelper } /// - /// Авторизация через jwt-токен keycloak + /// Авторизация через jwt-токен keycloak /// /// /// /// - private static string CreateKeyCloakJwtToken(this AuthUser authUser, string keycloakGetTokenUrl) + private static string CreateKeyCloakJwtToken(this AuthUser authUser, string keycloakGetTokenUrl, HttpClient httpClient) { - var sharedClient = new HttpClient(); var parameters = new Dictionary { { "username", authUser.Username }, { "password", authUser.Password }, @@ -84,7 +83,7 @@ public static class ApiTokenHelper }; var encodedContent = new FormUrlEncodedContent(parameters); - using HttpResponseMessage response = sharedClient.PostAsync(keycloakGetTokenUrl, encodedContent).GetAwaiter().GetResult(); + using HttpResponseMessage response = httpClient.PostAsync(keycloakGetTokenUrl, encodedContent).GetAwaiter().GetResult(); if (response.IsSuccessStatusCode == true) { -- 2.45.2 From e892adbd96959ae0b1c2fe789cf89ecfa3cb6ba2 Mon Sep 17 00:00:00 2001 From: Olga Nemt Date: Mon, 3 Feb 2025 16:01:08 +0500 Subject: [PATCH 4/4] =?UTF-8?q?=D0=A3=D0=B1=D1=80=D0=B0=D0=BD=20ApiTokenHe?= =?UTF-8?q?lper=20=D0=B8=D0=B7=20Clients=20=D0=B8=20=D0=B4=D0=BE=D0=B1?= =?UTF-8?q?=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=20=D0=B2=20IntegrationTests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ApiTokenHelper.cs | 37 +------------------ 1 file changed, 2 insertions(+), 35 deletions(-) rename {DD.Persistence.Client/Helpers => DD.Persistence.IntegrationTests}/ApiTokenHelper.cs (58%) diff --git a/DD.Persistence.Client/Helpers/ApiTokenHelper.cs b/DD.Persistence.IntegrationTests/ApiTokenHelper.cs similarity index 58% rename from DD.Persistence.Client/Helpers/ApiTokenHelper.cs rename to DD.Persistence.IntegrationTests/ApiTokenHelper.cs index 3487dcb..a93fb0d 100644 --- a/DD.Persistence.Client/Helpers/ApiTokenHelper.cs +++ b/DD.Persistence.IntegrationTests/ApiTokenHelper.cs @@ -6,7 +6,7 @@ using System.Net.Http.Headers; using System.Security.Claims; using System.Text.Json; -namespace DD.Persistence.Client.Helpers; +namespace DD.Persistence.IntegrationTests; /// ///  Класс, позволяющий генерировать api-token @@ -24,14 +24,8 @@ public static class ApiTokenHelper var authUser = configuration .GetSection(nameof(AuthUser)) .Get()!; - var needUseKeyCloak = configuration - .GetSection("NeedUseKeyCloak") - .Get()!; - var keycloakGetTokenUrl = configuration.GetSection("KeycloakGetTokenUrl").Get() ?? string.Empty; - var jwtToken = needUseKeyCloak - ? authUser.CreateKeyCloakJwtToken(keycloakGetTokenUrl, httpClient) - : authUser.CreateDefaultJwtToken(); + var jwtToken = authUser.CreateDefaultJwtToken(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); } @@ -66,31 +60,4 @@ public static class ApiTokenHelper var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } - - /// - /// Авторизация через jwt-токен keycloak - /// - /// - /// - /// - private static string CreateKeyCloakJwtToken(this AuthUser authUser, string keycloakGetTokenUrl, HttpClient httpClient) - { - var parameters = new Dictionary { - { "username", authUser.Username }, - { "password", authUser.Password }, - { "client_id", authUser.ClientId }, - { "grant_type", authUser.GrantType }, - }; - var encodedContent = new FormUrlEncodedContent(parameters); - - using HttpResponseMessage response = httpClient.PostAsync(keycloakGetTokenUrl, encodedContent).GetAwaiter().GetResult(); - - if (response.IsSuccessStatusCode == true) - { - var data = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); - var token = JsonSerializer.Deserialize(data)!; - return token.AccessToken; - } - return String.Empty; - } } -- 2.45.2