#384 Авторизации + получение id пользователя в контроллерах #3

Merged
on.nemtina merged 7 commits from PersistenceClient into master 2024-11-25 17:09:22 +05:00
8 changed files with 121 additions and 8 deletions
Showing only changes of commit 6518aeabf1 - Show all commits

View File

@ -4,5 +4,12 @@
"Port": 5432, "Port": 5432,
"Username": "postgres", "Username": "postgres",
"Password": "q" "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": "*", "AllowedHosts": "*",
"Authentication": { "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", "Audience": "account",
"ValidIssuer": "http://localhost:8080/realms/TestRealm", "ValidIssuer": "http://192.168.0.10:8321/realms/Persistence",
"AuthorizationUrl": "http://localhost:8080/realms/TestRealm/protocol/openid-connect/auth" "AuthorizationUrl": "http://192.168.0.10:8321/realms/Persistence/protocol/openid-connect/auth"
} }
} }

View File

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

View File

@ -1,4 +1,4 @@
using System.Net; using System.Net;
using Mapster; using Mapster;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Persistence.Client; using Persistence.Client;

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.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Refit" Version="8.0.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" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2"> <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>

View File

@ -3,10 +3,12 @@ using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Persistence.API;
using Persistence.Database.Model; using Persistence.Database.Model;
using Persistence.Database.Postgres; using Persistence.Database.Postgres;
using Persistence.API;
using Refit; using Refit;
using RestSharp;
using System.Net.Http.Headers;
using System.Text.Json; using System.Text.Json;
using Persistence.Database.Postgres; using Persistence.Database.Postgres;
using System.Net.Http.Headers; using System.Net.Http.Headers;
@ -26,6 +28,8 @@ public class WebAppFactoryFixture : WebApplicationFactory<Startup>
private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions)); private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
private readonly string connectionString; private readonly string connectionString;
private readonly KeyCloakUser keycloakTestUser;
public readonly string KeycloakGetTokenUrl;
public WebAppFactoryFixture() public WebAppFactoryFixture()
{ {
@ -35,6 +39,10 @@ public class WebAppFactoryFixture : WebApplicationFactory<Startup>
var dbConnection = configuration.GetSection("DbConnection").Get<DbConnection>()!; var dbConnection = configuration.GetSection("DbConnection").Get<DbConnection>()!;
connectionString = dbConnection.GetConnectionString(); connectionString = dbConnection.GetConnectionString();
keycloakTestUser = configuration.GetSection("KeycloakTestUser").Get<KeyCloakUser>()!;
KeycloakGetTokenUrl = configuration.GetSection("KeycloakGetTokenUrl").Value!;
} }
protected override void ConfigureWebHost(IWebHostBuilder builder) protected override void ConfigureWebHost(IWebHostBuilder builder)
@ -62,8 +70,70 @@ public class WebAppFactoryFixture : WebApplicationFactory<Startup>
var dbContext = scopedServices.GetRequiredService<PersistenceDbContext>(); var dbContext = scopedServices.GetRequiredService<PersistenceDbContext>();
dbContext.Database.EnsureCreatedAndMigrated(); dbContext.Database.EnsureCreatedAndMigrated();
//dbContext.Deposits.AddRange(Data.Defaults.Deposits);
dbContext.SaveChanges(); dbContext.SaveChanges();
}); });
} }
public override async ValueTask DisposeAsync()
{
var dbContext = new PersistenceDbContext(
new DbContextOptionsBuilder<PersistenceDbContext>()
.UseNpgsql(connectionString)
.Options);
await dbContext.Database.EnsureDeletedAsync();
}
public T GetHttpClient<T>(string uriSuffix)
{
var httpClient = CreateClient();
if (string.IsNullOrEmpty(uriSuffix))
return RestService.For<T>(httpClient, RefitSettings);
if (httpClient.BaseAddress is not null)
httpClient.BaseAddress = new Uri(httpClient.BaseAddress, uriSuffix);
return RestService.For<T>(httpClient, RefitSettings);
}
public async Task<T> GetAuthorizedHttpClient<T>(string uriSuffix)
{
var httpClient = await GetAuthorizedHttpClient();
if (string.IsNullOrEmpty(uriSuffix))
return RestService.For<T>(httpClient, RefitSettings);
if (httpClient.BaseAddress is not null)
httpClient.BaseAddress = new Uri(httpClient.BaseAddress, uriSuffix);
return RestService.For<T>(httpClient, RefitSettings);
}
private async Task<HttpClient> GetAuthorizedHttpClient()
{
var httpClient = CreateClient();
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;
}
} }