Merge pull request 'Удаление restsharp и использование обычного httpClient' (#22) from fix/#883-remove-restsharp into master
All checks were successful
Unit tests / test (push) Successful in 1m30s

Reviewed-on: #22
This commit is contained in:
on.nemtina 2025-02-03 16:21:32 +05:00
commit a9652be320
4 changed files with 63 additions and 82 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,80 +0,0 @@
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;
public static class ApiTokenHelper
{
public static void Authorize(this HttpClient httpClient, IConfiguration configuration)
{
var authUser = configuration
.GetSection(nameof(AuthUser))
.Get<AuthUser>()!;
var needUseKeyCloak = configuration
.GetSection("NeedUseKeyCloak")
.Get<bool>()!;
var keycloakGetTokenUrl = configuration.GetSection("KeycloakGetTokenUrl").Get<string>() ?? string.Empty;
var jwtToken = needUseKeyCloak
? 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);
}
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 tokenDescriptor = new SecurityTokenDescriptor
{
Issuer = JwtParams.Issuer,
Audience = JwtParams.Audience,
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(JwtParams.SecurityKey, SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
private static string CreateKeyCloakJwtToken(this AuthUser authUser, string keycloakGetTokenUrl)
{
var restClient = new RestClient();
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);
var keycloakResponse = restClient.Post(request);
if (keycloakResponse.IsSuccessful && !String.IsNullOrEmpty(keycloakResponse.Content))
{
var token = JsonSerializer.Deserialize<JwtToken>(keycloakResponse.Content)!;
return token.AccessToken;
}
return String.Empty;
}
}

View File

@ -0,0 +1,63 @@
using DD.Persistence.Models.Configurations;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text.Json;
namespace DD.Persistence.IntegrationTests;
/// <summary>
///  Класс, позволяющий генерировать api-token
/// </summary>
public static class ApiTokenHelper
{
/// <summary>
/// Метод авторизации
/// </summary>
/// <param name="httpClient"></param>
/// <param name="configuration"></param>
/// <returns></returns>
public static void Authorize(this HttpClient httpClient, IConfiguration configuration)
{
var authUser = configuration
.GetSection(nameof(AuthUser))
.Get<AuthUser>()!;
var jwtToken = authUser.CreateDefaultJwtToken();
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 tokenDescriptor = new SecurityTokenDescriptor
{
Issuer = JwtParams.Issuer,
Audience = JwtParams.Audience,
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(JwtParams.SecurityKey, SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}

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;