Удаление restsharp и использование обычного httpClient

This commit is contained in:
Оля Бизюкова 2025-01-31 16:07:17 +05:00
parent 634d82f237
commit 72dd365ffe
4 changed files with 49 additions and 34 deletions

View File

@ -52,7 +52,6 @@
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.3.0" />
<PackageReference Include="Refit" Version="8.0.0" />
<PackageReference Include="Refit.HttpClientFactory" Version="8.0.0" />
<PackageReference Include="RestSharp" Version="112.1.0" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="9.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.3.0" />
</ItemGroup>

View File

@ -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;
/// <summary>
/// Êëàññ, ïîçâîëÿþùèé ãåíåðèðîâàòü api-token
/// </summary>
public static class ApiTokenHelper
{
public static void Authorize(this HttpClient httpClient, IConfiguration configuration)
/// <summary>
/// Ìåòîä àâòîðèàöèè
/// </summary>
/// <param name="httpClient"></param>
/// <param name="configuration"></param>
/// <returns></returns>
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>() ?? 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);
}
/// <summary>
/// Àâòîðèçàöèÿ ÷åðåç ñîáñòâåííûé jwt-òîêåí
/// </summary>
/// <param name="authUser"></param>
/// <returns></returns>
private static string CreateDefaultJwtToken(this AuthUser authUser)
{
var nameIdetifier = Guid.NewGuid().ToString();
var claims = new List<Claim>()
{
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<Claim>()
{
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)
/// <summary>
/// Àâòîðèçàöèÿ ÷åðåç jwt-òîêåí keycloak
/// </summary>
/// <param name="authUser"></param>
/// <param name="keycloakGetTokenUrl"></param>
/// <returns></returns>
private static async Task<string> CreateKeyCloakJwtToken(this AuthUser authUser, string keycloakGetTokenUrl)
{
var restClient = new RestClient();
var sharedClient = new HttpClient();
var parameters = new Dictionary<string, string> {
{ "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<JwtToken>(keycloakResponse.Content)!;
var data = await response.Content.ReadAsStreamAsync();
var token = JsonSerializer.Deserialize<JwtToken>(data)!;
return token.AccessToken;
}
return String.Empty;
}
}

View File

@ -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;
}

View File

@ -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;