Авторизация в интеграционных тестах

This commit is contained in:
Olga Nemt 2024-11-21 11:41:53 +05:00
parent 3a1ea55be2
commit 098c180b12
8 changed files with 87 additions and 14 deletions

View File

@ -4,5 +4,12 @@
"Port": 5432,
"Username": "postgres",
"Password": "q"
}
},
"KeycloakTestUser": {
"username": "myuser",
"password": 12345,
"clientId": "webapi",
"grantType": "password"
},
"KeycloakGetTokenUrl": "http://192.168.0.10:8321/realms/Persistence/protocol/openid-connect/token"
}

View File

@ -10,9 +10,9 @@
},
"AllowedHosts": "*",
"Authentication": {
"MetadataAddress": "http://localhost:8080/realms/TestRealm/.well-known/openid-configuration",
"MetadataAddress": "http://192.168.0.10:8321/realms/Persistence/.well-known/openid-configuration",
"Audience": "account",
"ValidIssuer": "http://localhost:8080/realms/TestRealm",
"AuthorizationUrl": "http://localhost:8080/realms/TestRealm/protocol/openid-connect/auth"
"ValidIssuer": "http://192.168.0.10:8321/realms/Persistence",
"AuthorizationUrl": "http://192.168.0.10:8321/realms/Persistence/protocol/openid-connect/auth"
}
}

View File

@ -11,7 +11,7 @@ public class DataSaubControllerTest : TimeSeriesBaseControllerTest<DataSaub, Dat
BitDepth = 2,
BlockPosition = 3,
BlockSpeed = 4,
Date = DateTimeOffset.Now,
Date = DateTimeOffset.UtcNow,
Flow = 5,
HookWeight = 6,
Id = 7,

View File

@ -23,7 +23,10 @@ public abstract class TimeSeriesBaseControllerTest<TEntity, TDto> : BaseIntegrat
{
dbContext.CleanupDbSet<TEntity>();
client = factory.GetAuthorizedHttpClient<ITimeSeriesClient<TDto>>(string.Empty);
Task.Run(async () =>
{
client = await factory.GetAuthorizedHttpClient<ITimeSeriesClient<TDto>>(string.Empty);
}).Wait();
}
public async Task InsertRangeSuccess(TDto dto)

View File

@ -0,0 +1,8 @@
using System.Text.Json.Serialization;
namespace Persistence.IntegrationTests;
public class JwtToken
{
[JsonPropertyName("access_token")]
public required string AccessToken { get; set; }
}

View File

@ -0,0 +1,27 @@
namespace Persistence.IntegrationTests;
/// <summary>
/// настройки credentials для пользователя в KeyCloak
/// </summary>
public class KeyCloakUser
{
/// <summary>
///
/// </summary>
public required string Username { get; set; }
/// <summary>
///
/// </summary>
public required string Password { get; set; }
/// <summary>
///
/// </summary>
public required string ClientId { get; set; }
/// <summary>
///
/// </summary>
public required string GrantType { get; set; }
}

View File

@ -15,6 +15,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Refit" Version="8.0.0" />
<PackageReference Include="RestSharp" Version="112.1.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>

View File

@ -3,12 +3,13 @@ using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Persistence.API;
using Persistence.Database.Model;
using Persistence.Database.Postgres;
using Persistence.API;
using Refit;
using System.Text.Json;
using RestSharp;
using System.Net.Http.Headers;
using System.Text.Json;
namespace Persistence.IntegrationTests;
public class WebAppFactoryFixture : WebApplicationFactory<Startup>
@ -23,6 +24,8 @@ public class WebAppFactoryFixture : WebApplicationFactory<Startup>
private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
private readonly string connectionString;
private readonly KeyCloakUser keycloakTestUser;
public readonly string KeycloakGetTokenUrl;
public WebAppFactoryFixture()
{
@ -32,6 +35,10 @@ public class WebAppFactoryFixture : WebApplicationFactory<Startup>
var dbConnection = configuration.GetSection("DbConnection").Get<DbConnection>()!;
connectionString = dbConnection.GetConnectionString();
keycloakTestUser = configuration.GetSection("KeycloakTestUser").Get<KeyCloakUser>()!;
KeycloakGetTokenUrl = configuration.GetSection("KeycloakGetTokenUrl").Value!;
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
@ -53,7 +60,6 @@ public class WebAppFactoryFixture : WebApplicationFactory<Startup>
var dbContext = scopedServices.GetRequiredService<PersistenceDbContext>();
dbContext.Database.EnsureCreatedAndMigrated();
//dbContext.Deposits.AddRange(Data.Defaults.Deposits);
dbContext.SaveChanges();
});
}
@ -80,9 +86,9 @@ public class WebAppFactoryFixture : WebApplicationFactory<Startup>
return RestService.For<T>(httpClient, RefitSettings);
}
public T GetAuthorizedHttpClient<T>(string uriSuffix)
public async Task<T> GetAuthorizedHttpClient<T>(string uriSuffix)
{
var httpClient = GetAuthorizedHttpClient();
var httpClient = await GetAuthorizedHttpClient();
if (string.IsNullOrEmpty(uriSuffix))
return RestService.For<T>(httpClient, RefitSettings);
@ -92,11 +98,32 @@ public class WebAppFactoryFixture : WebApplicationFactory<Startup>
return RestService.For<T>(httpClient, RefitSettings);
}
private HttpClient GetAuthorizedHttpClient()
private async Task<HttpClient> GetAuthorizedHttpClient()
{
var httpClient = CreateClient();
////var jwtToken = ApiTokenHelper.GetAdminUserToken();
//httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
var token = await GetTokenAsync();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return httpClient;
}
private async Task<string> GetTokenAsync()
{
var restClient = new RestClient();
var request = new RestRequest(KeycloakGetTokenUrl, Method.Post);
request.AddParameter("username", keycloakTestUser.Username);
request.AddParameter("password", keycloakTestUser.Password);
request.AddParameter("client_id", keycloakTestUser.ClientId);
request.AddParameter("grant_type", keycloakTestUser.GrantType);
var keyCloackResponse = await restClient.PostAsync(request);
if (keyCloackResponse.IsSuccessful && !String.IsNullOrEmpty(keyCloackResponse.Content))
{
var token = JsonSerializer.Deserialize<JwtToken>(keyCloackResponse.Content)!;
return token.AccessToken;
}
return String.Empty;
}
}