From d9cbc9022dbbc7f479d5e11d715b83875f58d3ee Mon Sep 17 00:00:00 2001 From: Roman Efremov Date: Thu, 21 Nov 2024 14:50:36 +0500 Subject: [PATCH 1/3] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20Persistence.Client?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Persistence.Client/Clients/ISetpointClient.cs | 24 +++++++++ .../Clients/ITimeSeriesClient.cs | 2 +- Persistence.Client/Helpers/ApiTokenHelper.cs | 43 +++++++++++++++ Persistence.Client/Persistence.Client.csproj | 18 +++++++ .../PersistenceClientFactory.cs | 48 +++++++++++++++++ .../Clients/ISetpointClient.cs | 25 --------- .../Controllers/DataSaubControllerTest.cs | 3 +- .../Controllers/SetpointControllerTest.cs | 27 ++++++---- .../TimeSeriesBaseControllerTest.cs | 30 +++++------ .../Persistence.IntegrationTests.csproj | 1 + .../TestHttpClientFactory.cs | 16 ++++++ .../WebAppFactoryFixture.cs | 54 ++++--------------- Persistence.sln | 8 ++- 13 files changed, 201 insertions(+), 98 deletions(-) create mode 100644 Persistence.Client/Clients/ISetpointClient.cs rename {Persistence.IntegrationTests => Persistence.Client}/Clients/ITimeSeriesClient.cs (88%) create mode 100644 Persistence.Client/Helpers/ApiTokenHelper.cs create mode 100644 Persistence.Client/Persistence.Client.csproj create mode 100644 Persistence.Client/PersistenceClientFactory.cs delete mode 100644 Persistence.IntegrationTests/Clients/ISetpointClient.cs create mode 100644 Persistence.IntegrationTests/TestHttpClientFactory.cs diff --git a/Persistence.Client/Clients/ISetpointClient.cs b/Persistence.Client/Clients/ISetpointClient.cs new file mode 100644 index 0000000..49733f0 --- /dev/null +++ b/Persistence.Client/Clients/ISetpointClient.cs @@ -0,0 +1,24 @@ +using Persistence.Models; +using Refit; + +namespace Persistence.Client.Clients; + +/// +/// Интерфейс для тестирования API, предназначенного для работы с уставками +/// +public interface ISetpointClient +{ + private const string BaseRoute = "/api/setpoint"; + + [Get($"{BaseRoute}/current")] + Task>> GetCurrent([Query(CollectionFormat.Multi)] IEnumerable setpointKeys); + + [Get($"{BaseRoute}/history")] + Task>> GetHistory([Query(CollectionFormat.Multi)] IEnumerable setpointKeys, [Query] DateTimeOffset historyMoment); + + [Get($"{BaseRoute}/log")] + Task>>> GetLog([Query(CollectionFormat.Multi)] IEnumerable setpointKeys); + + [Post($"{BaseRoute}/")] + Task Save(Guid setpointKey, object newValue); +} diff --git a/Persistence.IntegrationTests/Clients/ITimeSeriesClient.cs b/Persistence.Client/Clients/ITimeSeriesClient.cs similarity index 88% rename from Persistence.IntegrationTests/Clients/ITimeSeriesClient.cs rename to Persistence.Client/Clients/ITimeSeriesClient.cs index 03b7638..8456fa2 100644 --- a/Persistence.IntegrationTests/Clients/ITimeSeriesClient.cs +++ b/Persistence.Client/Clients/ITimeSeriesClient.cs @@ -1,7 +1,7 @@ using Microsoft.AspNetCore.Mvc; using Refit; -namespace Persistence.IntegrationTests.Clients; +namespace Persistence.Client.Clients; public interface ITimeSeriesClient where TDto : class, new() { diff --git a/Persistence.Client/Helpers/ApiTokenHelper.cs b/Persistence.Client/Helpers/ApiTokenHelper.cs new file mode 100644 index 0000000..479ba60 --- /dev/null +++ b/Persistence.Client/Helpers/ApiTokenHelper.cs @@ -0,0 +1,43 @@ +namespace Persistence.Client.Helpers; +public static class ApiTokenHelper +{ + public static string GetAdminUserToken() + { + //var user = new User() + //{ + // Id = 1, + // IdCompany = 1, + // Login = "test_user" + //}; + //var roles = new[] { "root" }; + + return string.Empty; + } + + //private static string CreateToken(User user, IEnumerable roles) + //{ + // var claims = new List + // { + // new("id", user.Id.ToString()), + // new(ClaimsIdentity.DefaultNameClaimType, user.Login), + // new("idCompany", user.IdCompany.ToString()), + // }; + + // claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); + + // const string secret = "супер секретный ключ для шифрования"; + + // var key = Encoding.ASCII.GetBytes(secret); + // var tokenDescriptor = new SecurityTokenDescriptor + // { + // Issuer = "a", + // Audience = "a", + // Subject = new ClaimsIdentity(claims), + // Expires = DateTime.UtcNow.AddHours(1), + // SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) + // }; + // var tokenHandler = new JwtSecurityTokenHandler(); + // var token = tokenHandler.CreateToken(tokenDescriptor); + // return tokenHandler.WriteToken(token); + //} +} diff --git a/Persistence.Client/Persistence.Client.csproj b/Persistence.Client/Persistence.Client.csproj new file mode 100644 index 0000000..c7ed8f5 --- /dev/null +++ b/Persistence.Client/Persistence.Client.csproj @@ -0,0 +1,18 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + diff --git a/Persistence.Client/PersistenceClientFactory.cs b/Persistence.Client/PersistenceClientFactory.cs new file mode 100644 index 0000000..9c3be71 --- /dev/null +++ b/Persistence.Client/PersistenceClientFactory.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http.Headers; +using System.Net.Http; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using Newtonsoft.Json.Linq; +using Refit; +using Persistence.Client.Helpers; + +namespace Persistence.Client +{ + public static class PersistenceClientFactory + { + + private static readonly JsonSerializerOptions JsonSerializerOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true + }; + + private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions)); + + public static T GetClient(HttpClient client) + { + return RestService.For(client, RefitSettings); + } + + public static T GetClient(string baseUrl) + { + var client = new HttpClient(); + client.BaseAddress = new Uri(baseUrl); + + return RestService.For(client, RefitSettings); + } + + private static HttpClient GetAuthorizedClient() + { + var httpClient = new HttpClient(); + var jwtToken = ApiTokenHelper.GetAdminUserToken(); + httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); + + return httpClient; + } + } +} diff --git a/Persistence.IntegrationTests/Clients/ISetpointClient.cs b/Persistence.IntegrationTests/Clients/ISetpointClient.cs deleted file mode 100644 index a4f79b5..0000000 --- a/Persistence.IntegrationTests/Clients/ISetpointClient.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Persistence.Models; -using Refit; - -namespace Persistence.IntegrationTests.Clients -{ - /// - /// Интерфейс для тестирования API, предназначенного для работы с уставками - /// - public interface ISetpointClient - { - private const string BaseRoute = "/api/setpoint"; - - [Get($"{BaseRoute}/current")] - Task>> GetCurrent([Query(CollectionFormat.Multi)] IEnumerable setpointKeys); - - [Get($"{BaseRoute}/history")] - Task>> GetHistory([Query(CollectionFormat.Multi)] IEnumerable setpointKeys, [Query] DateTimeOffset historyMoment); - - [Get($"{BaseRoute}/log")] - Task>>> GetLog([Query(CollectionFormat.Multi)] IEnumerable setpointKeys); - - [Post($"{BaseRoute}/")] - Task Save(Guid setpointKey, object newValue); - } -} diff --git a/Persistence.IntegrationTests/Controllers/DataSaubControllerTest.cs b/Persistence.IntegrationTests/Controllers/DataSaubControllerTest.cs index 025492a..8708960 100644 --- a/Persistence.IntegrationTests/Controllers/DataSaubControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/DataSaubControllerTest.cs @@ -1,4 +1,5 @@ -using Persistence.Database.Model; +using Persistence.Client; +using Persistence.Database.Model; using Persistence.Repository.Data; using Xunit; diff --git a/Persistence.IntegrationTests/Controllers/SetpointControllerTest.cs b/Persistence.IntegrationTests/Controllers/SetpointControllerTest.cs index 2fcfc52..f865ce2 100644 --- a/Persistence.IntegrationTests/Controllers/SetpointControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/SetpointControllerTest.cs @@ -1,12 +1,14 @@ using System.Net; -using Persistence.IntegrationTests.Clients; +using Microsoft.Extensions.DependencyInjection; +using Persistence.Client; +using Persistence.Client.Clients; using Xunit; namespace Persistence.IntegrationTests.Controllers { public class SetpointControllerTest : BaseIntegrationTest { - private ISetpointClient client; + private ISetpointClient setpointClient; private class TestObject { public string? value1 { get; set; } @@ -14,7 +16,12 @@ namespace Persistence.IntegrationTests.Controllers } public SetpointControllerTest(WebAppFactoryFixture factory) : base(factory) { - client = factory.GetHttpClient(string.Empty); + var scope = factory.Services.CreateScope(); + var httpClient = scope.ServiceProvider + .GetRequiredService() + .CreateClient(); + + setpointClient = PersistenceClientFactory.GetClient(httpClient); } [Fact] @@ -28,7 +35,7 @@ namespace Persistence.IntegrationTests.Controllers }; //act - var response = await client.GetCurrent(setpointKeys); + var response = await setpointClient.GetCurrent(setpointKeys); //assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -43,7 +50,7 @@ namespace Persistence.IntegrationTests.Controllers var setpointKey = await Save(); //act - var response = await client.GetCurrent([setpointKey]); + var response = await setpointClient.GetCurrent([setpointKey]); //assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -64,7 +71,7 @@ namespace Persistence.IntegrationTests.Controllers var historyMoment = DateTimeOffset.UtcNow; //act - var response = await client.GetHistory(setpointKeys, historyMoment); + var response = await setpointClient.GetHistory(setpointKeys, historyMoment); //assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -81,7 +88,7 @@ namespace Persistence.IntegrationTests.Controllers historyMoment = historyMoment.AddDays(1); //act - var response = await client.GetHistory([setpointKey], historyMoment); + var response = await setpointClient.GetHistory([setpointKey], historyMoment); //assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -101,7 +108,7 @@ namespace Persistence.IntegrationTests.Controllers }; //act - var response = await client.GetLog(setpointKeys); + var response = await setpointClient.GetLog(setpointKeys); //assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -116,7 +123,7 @@ namespace Persistence.IntegrationTests.Controllers var setpointKey = await Save(); //act - var response = await client.GetLog([setpointKey]); + var response = await setpointClient.GetLog([setpointKey]); //assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -142,7 +149,7 @@ namespace Persistence.IntegrationTests.Controllers }; //act - var response = await client.Save(setpointKey, setpointValue); + var response = await setpointClient.Save(setpointKey, setpointValue); //assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs b/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs index c63f094..59623a1 100644 --- a/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs @@ -1,15 +1,8 @@ -using Mapster; -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration.UserSecrets; -using Persistence.IntegrationTests.Clients; -using Persistence.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading.Tasks; +using System.Net; +using Mapster; +using Microsoft.Extensions.DependencyInjection; +using Persistence.Client; +using Persistence.Client.Clients; using Xunit; namespace Persistence.IntegrationTests.Controllers; @@ -17,13 +10,18 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat where TEntity : class where TDto : class, new() { - private ITimeSeriesClient client; + private ITimeSeriesClient timeSeriesClient; public TimeSeriesBaseControllerTest(WebAppFactoryFixture factory) : base(factory) { dbContext.CleanupDbSet(); - client = factory.GetAuthorizedHttpClient>(string.Empty); + var scope = factory.Services.CreateScope(); + var httpClient = scope.ServiceProvider + .GetRequiredService() + .CreateClient(); + + timeSeriesClient = PersistenceClientFactory.GetClient>(httpClient); } public async Task InsertRangeSuccess(TDto dto) @@ -32,7 +30,7 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat var expected = dto.Adapt(); //act - var response = await client.InsertRangeAsync(new TDto[] { expected }); + var response = await timeSeriesClient.InsertRangeAsync(new TDto[] { expected }); //assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -48,7 +46,7 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat dbContext.SaveChanges(); - var response = await client.GetAsync(beginDate, endDate); + var response = await timeSeriesClient.GetAsync(beginDate, endDate); //assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/Persistence.IntegrationTests/Persistence.IntegrationTests.csproj b/Persistence.IntegrationTests/Persistence.IntegrationTests.csproj index 912eeda..7d0116e 100644 --- a/Persistence.IntegrationTests/Persistence.IntegrationTests.csproj +++ b/Persistence.IntegrationTests/Persistence.IntegrationTests.csproj @@ -24,6 +24,7 @@ + diff --git a/Persistence.IntegrationTests/TestHttpClientFactory.cs b/Persistence.IntegrationTests/TestHttpClientFactory.cs new file mode 100644 index 0000000..1687f49 --- /dev/null +++ b/Persistence.IntegrationTests/TestHttpClientFactory.cs @@ -0,0 +1,16 @@ +namespace Persistence.IntegrationTests +{ + public class TestHttpClientFactory : IHttpClientFactory + { + private readonly WebAppFactoryFixture factory; + + public TestHttpClientFactory(WebAppFactoryFixture factory) + { + this.factory = factory; + } + public HttpClient CreateClient(string name) + { + return factory.CreateClient(); + } + } +} diff --git a/Persistence.IntegrationTests/WebAppFactoryFixture.cs b/Persistence.IntegrationTests/WebAppFactoryFixture.cs index ac73013..f932b83 100644 --- a/Persistence.IntegrationTests/WebAppFactoryFixture.cs +++ b/Persistence.IntegrationTests/WebAppFactoryFixture.cs @@ -10,6 +10,8 @@ using Refit; using System.Text.Json; using Persistence.Database.Postgres; using System.Net.Http.Headers; +using Persistence.Client; +using Microsoft.Extensions.DependencyInjection.Extensions; namespace Persistence.IntegrationTests; public class WebAppFactoryFixture : WebApplicationFactory @@ -47,57 +49,21 @@ public class WebAppFactoryFixture : WebApplicationFactory services.AddDbContext(options => options.UseNpgsql(connectionString)); - var serviceProvider = services.BuildServiceProvider(); + services.RemoveAll(); + services.AddSingleton(provider => + { + return new TestHttpClientFactory(this); + }); + + var serviceProvider = services.BuildServiceProvider(); using var scope = serviceProvider.CreateScope(); var scopedServices = scope.ServiceProvider; - var dbContext = scopedServices.GetRequiredService(); + var dbContext = scopedServices.GetRequiredService(); dbContext.Database.EnsureCreatedAndMigrated(); //dbContext.Deposits.AddRange(Data.Defaults.Deposits); dbContext.SaveChanges(); }); } - - public override async ValueTask DisposeAsync() - { - var dbContext = new PersistenceDbContext( - new DbContextOptionsBuilder() - .UseNpgsql(connectionString) - .Options); - - await dbContext.Database.EnsureDeletedAsync(); - } - - public T GetHttpClient(string uriSuffix) - { - var httpClient = CreateClient(); - if (string.IsNullOrEmpty(uriSuffix)) - return RestService.For(httpClient, RefitSettings); - - if (httpClient.BaseAddress is not null) - httpClient.BaseAddress = new Uri(httpClient.BaseAddress, uriSuffix); - - return RestService.For(httpClient, RefitSettings); - } - - public T GetAuthorizedHttpClient(string uriSuffix) - { - var httpClient = GetAuthorizedHttpClient(); - if (string.IsNullOrEmpty(uriSuffix)) - return RestService.For(httpClient, RefitSettings); - - if (httpClient.BaseAddress is not null) - httpClient.BaseAddress = new Uri(httpClient.BaseAddress, uriSuffix); - - return RestService.For(httpClient, RefitSettings); - } - - private HttpClient GetAuthorizedHttpClient() - { - var httpClient = CreateClient(); - ////var jwtToken = ApiTokenHelper.GetAdminUserToken(); - //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); - return httpClient; - } } diff --git a/Persistence.sln b/Persistence.sln index ce44190..a8115a8 100644 --- a/Persistence.sln +++ b/Persistence.sln @@ -13,7 +13,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Persistence.Database", "Per EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Persistence.IntegrationTests", "Persistence.IntegrationTests\Persistence.IntegrationTests.csproj", "{10752C25-3773-4081-A1F2-215A1D950126}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Persistence.Database.Postgres", "Persistence.Database.Postgres\Persistence.Database.Postgres.csproj", "{CC284D27-162D-490C-B6CF-74D666B7C5F3}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Persistence.Database.Postgres", "Persistence.Database.Postgres\Persistence.Database.Postgres.csproj", "{CC284D27-162D-490C-B6CF-74D666B7C5F3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Persistence.Client", "Persistence.Client\Persistence.Client.csproj", "{84B68660-48E6-4974-A4E5-517552D9DE23}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -45,6 +47,10 @@ Global {CC284D27-162D-490C-B6CF-74D666B7C5F3}.Debug|Any CPU.Build.0 = Debug|Any CPU {CC284D27-162D-490C-B6CF-74D666B7C5F3}.Release|Any CPU.ActiveCfg = Release|Any CPU {CC284D27-162D-490C-B6CF-74D666B7C5F3}.Release|Any CPU.Build.0 = Release|Any CPU + {84B68660-48E6-4974-A4E5-517552D9DE23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {84B68660-48E6-4974-A4E5-517552D9DE23}.Debug|Any CPU.Build.0 = Debug|Any CPU + {84B68660-48E6-4974-A4E5-517552D9DE23}.Release|Any CPU.ActiveCfg = Release|Any CPU + {84B68660-48E6-4974-A4E5-517552D9DE23}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 3806e395eb804cc4e8289d609575fedd16e11b3c Mon Sep 17 00:00:00 2001 From: Roman Efremov Date: Mon, 25 Nov 2024 10:09:38 +0500 Subject: [PATCH 2/3] =?UTF-8?q?=D0=A0=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D1=82=D1=8C=20=D0=B0=D0=B2=D1=82=D0=BE=D1=80=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D1=8E=20=D0=B4=D0=BB=D1=8F=20Persisten?= =?UTF-8?q?ce.Client?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/SetpointController.cs | 4 +- Persistence.API/DependencyInjection.cs | 191 +++++++++++++----- .../Properties/launchSettings.json | 2 +- Persistence.API/appsettings.Development.json | 3 +- Persistence.API/appsettings.Tests.json | 5 +- Persistence.Client/Helpers/ApiTokenHelper.cs | 99 +++++---- Persistence.Client/Persistence.Client.csproj | 7 + .../PersistenceClientFactory.cs | 42 ++-- .../ApiTokenHelper.cs | 43 ---- .../Controllers/SetpointControllerTest.cs | 7 +- .../TimeSeriesBaseControllerTest.cs | 7 +- Persistence.IntegrationTests/JwtToken.cs | 8 - Persistence.IntegrationTests/KeyCloakUser.cs | 27 --- .../WebAppFactoryFixture.cs | 109 ++-------- Persistence/Models/Configurations/AuthUser.cs | 12 ++ .../Models/Configurations/JwtParams.cs | 18 ++ Persistence/Models/Configurations/JwtToken.cs | 10 + Persistence/Persistence.csproj | 1 + 18 files changed, 297 insertions(+), 298 deletions(-) delete mode 100644 Persistence.IntegrationTests/ApiTokenHelper.cs delete mode 100644 Persistence.IntegrationTests/JwtToken.cs delete mode 100644 Persistence.IntegrationTests/KeyCloakUser.cs create mode 100644 Persistence/Models/Configurations/AuthUser.cs create mode 100644 Persistence/Models/Configurations/JwtParams.cs create mode 100644 Persistence/Models/Configurations/JwtToken.cs diff --git a/Persistence.API/Controllers/SetpointController.cs b/Persistence.API/Controllers/SetpointController.cs index 14f966c..9a6bd61 100644 --- a/Persistence.API/Controllers/SetpointController.cs +++ b/Persistence.API/Controllers/SetpointController.cs @@ -1,10 +1,12 @@ -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; using Persistence.Models; using Persistence.Repositories; namespace Persistence.API.Controllers { [ApiController] + [Authorize] [Route("api/[controller]")] public class SetpointController : ControllerBase, ISetpointApi { diff --git a/Persistence.API/DependencyInjection.cs b/Persistence.API/DependencyInjection.cs index e91e3a0..2762881 100644 --- a/Persistence.API/DependencyInjection.cs +++ b/Persistence.API/DependencyInjection.cs @@ -1,7 +1,13 @@ -using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Models; +using Persistence.Models; +using Persistence.Models.Configurations; +using System.Data.Common; +using System.Text; using System.Text.Json.Nodes; namespace Persistence.API; @@ -30,59 +36,144 @@ public static class DependencyInjection }); c.SwaggerDoc("v1", new OpenApiInfo { Title = "Persistence web api", Version = "v1" }); - c.AddSecurityDefinition("Keycloack", new OpenApiSecurityScheme - { - Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'", - Name = "Authorization", - In = ParameterLocation.Header, - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - Implicit = new OpenApiOAuthFlow - { - AuthorizationUrl = new Uri(configuration["Authentication:AuthorizationUrl"]), - } - } - }); - c.AddSecurityRequirement(new OpenApiSecurityRequirement() - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "Keycloack" - }, - Scheme = "Bearer", - Name = "Bearer", - In = ParameterLocation.Header, - }, - new List() - } - }); + var needUseKeyCloak = configuration.GetSection("NeedUseKeyCloak").Get(); + if (needUseKeyCloak) + { + c.AddSecurityDefinition("Keycloack", new OpenApiSecurityScheme + { + Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'", + Name = "Authorization", + In = ParameterLocation.Header, + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows + { + Implicit = new OpenApiOAuthFlow + { + AuthorizationUrl = new Uri(configuration["Authentication:AuthorizationUrl"]), + } + } + }); - //var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; - //var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); - //var includeControllerXmlComment = true; - //c.IncludeXmlComments(xmlPath, includeControllerXmlComment); - //c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "AsbCloudApp.xml"), includeControllerXmlComment); - }); + c.AddSecurityRequirement(new OpenApiSecurityRequirement() + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "Keycloack" + }, + Scheme = "Bearer", + Name = "Bearer", + In = ParameterLocation.Header, + }, + new List() + } + }); + } + else + { + c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme + { + Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'", + Name = "Authorization", + In = ParameterLocation.Header, + Type = SecuritySchemeType.ApiKey, + Scheme = "Bearer", + }); + + c.AddSecurityRequirement(new OpenApiSecurityRequirement() + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "Bearer" + }, + Scheme = "oauth2", + Name = "Bearer", + In = ParameterLocation.Header, + }, + new List() + } + }); + } + + //var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + //var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + //var includeControllerXmlComment = true; + //c.IncludeXmlComments(xmlPath, includeControllerXmlComment); + //c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "AsbCloudApp.xml"), includeControllerXmlComment); + }); } public static void AddJWTAuthentication(this IServiceCollection services, IConfiguration configuration) { - services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) - .AddJwtBearer(o => - { - o.RequireHttpsMetadata = false; - o.Audience = configuration["Authentication:Audience"]; - o.MetadataAddress = configuration["Authentication:MetadataAddress"]!; - o.TokenValidationParameters = new TokenValidationParameters - { - ValidIssuer = configuration["Authentication:ValidIssuer"], - }; - }); - } + var needUseKeyCloak = configuration + .GetSection("NeedUseKeyCloak") + .Get(); + if (needUseKeyCloak) services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.RequireHttpsMetadata = false; + options.Audience = configuration["Authentication:Audience"]; + options.MetadataAddress = configuration["Authentication:MetadataAddress"]!; + options.TokenValidationParameters = new TokenValidationParameters + { + ValidIssuer = configuration["Authentication:ValidIssuer"], + }; + }); + else services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.RequireHttpsMetadata = false; + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidIssuer = JwtParams.Issuer, + ValidateAudience = true, + ValidAudience = JwtParams.Audience, + ValidateLifetime = true, + IssuerSigningKey = JwtParams.SecurityKey, + ValidateIssuerSigningKey = false + }; + options.Events = new JwtBearerEvents + { + OnMessageReceived = context => + { + var accessToken = context.Request.Headers["Authorization"] + .ToString() + .Replace(JwtBearerDefaults.AuthenticationScheme, string.Empty) + .Trim(); + + context.Token = accessToken; + + return Task.CompletedTask; + }, + OnTokenValidated = context => + { + var username = context.Principal?.Claims + .FirstOrDefault(e => e.Type == "username")?.Value; + + var password = context.Principal?.Claims + .FirstOrDefault(e => e.Type == "password")?.Value; + + var keyCloakUser = configuration + .GetSection(nameof(AuthUser)) + .Get()!; + + if (username != keyCloakUser.Username || password != keyCloakUser.Password) + { + context.Fail("username or password did not match"); + } + + return Task.CompletedTask; + } + }; + }); + } } diff --git a/Persistence.API/Properties/launchSettings.json b/Persistence.API/Properties/launchSettings.json index c2ccc25..52a969d 100644 --- a/Persistence.API/Properties/launchSettings.json +++ b/Persistence.API/Properties/launchSettings.json @@ -8,7 +8,7 @@ "ASPNETCORE_ENVIRONMENT": "Development" }, "dotnetRunMessages": true, - "applicationUrl": "http://localhost:5032" + "applicationUrl": "http://localhost:13616" }, "IIS Express": { "commandName": "IISExpress", diff --git a/Persistence.API/appsettings.Development.json b/Persistence.API/appsettings.Development.json index 0c208ae..896c0b7 100644 --- a/Persistence.API/appsettings.Development.json +++ b/Persistence.API/appsettings.Development.json @@ -4,5 +4,6 @@ "Default": "Information", "Microsoft.AspNetCore": "Warning" } - } + }, + "NeedUseKeyCloak": false } diff --git a/Persistence.API/appsettings.Tests.json b/Persistence.API/appsettings.Tests.json index 033464f..6201a8f 100644 --- a/Persistence.API/appsettings.Tests.json +++ b/Persistence.API/appsettings.Tests.json @@ -1,11 +1,12 @@ -{ +{ "DbConnection": { "Host": "localhost", "Port": 5432, "Username": "postgres", "Password": "q" }, - "KeycloakTestUser": { + "NeedUseKeyCloak": false, + "AuthUser": { "username": "myuser", "password": 12345, "clientId": "webapi", diff --git a/Persistence.Client/Helpers/ApiTokenHelper.cs b/Persistence.Client/Helpers/ApiTokenHelper.cs index 479ba60..e508922 100644 --- a/Persistence.Client/Helpers/ApiTokenHelper.cs +++ b/Persistence.Client/Helpers/ApiTokenHelper.cs @@ -1,43 +1,72 @@ -namespace Persistence.Client.Helpers; +using System.IdentityModel.Tokens.Jwt; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text.Json; +using Microsoft.Extensions.Configuration; +using Microsoft.IdentityModel.Tokens; +using Persistence.Models.Configurations; +using RestSharp; + +namespace Persistence.Client.Helpers; public static class ApiTokenHelper { - public static string GetAdminUserToken() - { - //var user = new User() - //{ - // Id = 1, - // IdCompany = 1, - // Login = "test_user" - //}; - //var roles = new[] { "root" }; + public static void Authorize(this HttpClient httpClient, IConfiguration configuration) + { + var authUser = configuration + .GetSection(nameof(AuthUser)) + .Get()!; + var needUseKeyCloak = configuration + .GetSection("NeedUseKeyCloak") + .Get()!; + var keycloakGetTokenUrl = configuration.GetSection("KeycloakGetTokenUrl").Get() ?? string.Empty; - return string.Empty; - } + var jwtToken = needUseKeyCloak + ? authUser.CreateKeyCloakJwtToken(keycloakGetTokenUrl) + : authUser.CreateDefaultJwtToken(); - //private static string CreateToken(User user, IEnumerable roles) - //{ - // var claims = new List - // { - // new("id", user.Id.ToString()), - // new(ClaimsIdentity.DefaultNameClaimType, user.Login), - // new("idCompany", user.IdCompany.ToString()), - // }; + httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); + } - // claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); + private static string CreateDefaultJwtToken(this AuthUser authUser) + { + var claims = new List() + { + new("client_id", authUser.ClientId), + new("username", authUser.Username), + new("password", authUser.Password), + new("grant_type", authUser.GrantType) + }; - // const string secret = "супер секретный ключ для шифрования"; + 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); + } - // var key = Encoding.ASCII.GetBytes(secret); - // var tokenDescriptor = new SecurityTokenDescriptor - // { - // Issuer = "a", - // Audience = "a", - // Subject = new ClaimsIdentity(claims), - // Expires = DateTime.UtcNow.AddHours(1), - // SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), 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 keyCloackResponse = restClient.Post(request); + if (keyCloackResponse.IsSuccessful && !String.IsNullOrEmpty(keyCloackResponse.Content)) + { + var token = JsonSerializer.Deserialize(keyCloackResponse.Content)!; + return token.AccessToken; + } + + return String.Empty; + } } diff --git a/Persistence.Client/Persistence.Client.csproj b/Persistence.Client/Persistence.Client.csproj index c7ed8f5..d699df7 100644 --- a/Persistence.Client/Persistence.Client.csproj +++ b/Persistence.Client/Persistence.Client.csproj @@ -7,12 +7,19 @@ + + + + + + + diff --git a/Persistence.Client/PersistenceClientFactory.cs b/Persistence.Client/PersistenceClientFactory.cs index 9c3be71..7a8daa8 100644 --- a/Persistence.Client/PersistenceClientFactory.cs +++ b/Persistence.Client/PersistenceClientFactory.cs @@ -1,48 +1,30 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http.Headers; -using System.Net.Http; -using System.Text; -using System.Text.Json; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; -using Refit; +using System.Text.Json; +using Microsoft.Extensions.Configuration; using Persistence.Client.Helpers; +using Persistence.Models.Configurations; +using Refit; namespace Persistence.Client { - public static class PersistenceClientFactory + public class PersistenceClientFactory { - private static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true }; - private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions)); - - public static T GetClient(HttpClient client) + private HttpClient httpClient; + public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IConfiguration configuration) { - return RestService.For(client, RefitSettings); + this.httpClient = httpClientFactory.CreateClient(); + + httpClient.Authorize(configuration); } - public static T GetClient(string baseUrl) + public T GetClient() { - var client = new HttpClient(); - client.BaseAddress = new Uri(baseUrl); - - return RestService.For(client, RefitSettings); - } - - private static HttpClient GetAuthorizedClient() - { - var httpClient = new HttpClient(); - var jwtToken = ApiTokenHelper.GetAdminUserToken(); - httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); - - return httpClient; + return RestService.For(httpClient, RefitSettings); } } } diff --git a/Persistence.IntegrationTests/ApiTokenHelper.cs b/Persistence.IntegrationTests/ApiTokenHelper.cs deleted file mode 100644 index 3c1fda2..0000000 --- a/Persistence.IntegrationTests/ApiTokenHelper.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace Persistence.IntegrationTests; -public static class ApiTokenHelper -{ - //public static string GetAdminUserToken() - //{ - // var user = new User() - // { - // Id = 1, - // IdCompany = 1, - // Login = "test_user" - // }; - // var roles = new[] { "root" }; - - // return CreateToken(user, roles); - //} - - //private static string CreateToken(User user, IEnumerable roles) - //{ - // var claims = new List - // { - // new("id", user.Id.ToString()), - // new(ClaimsIdentity.DefaultNameClaimType, user.Login), - // new("idCompany", user.IdCompany.ToString()), - // }; - - // claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); - - // const string secret = "супер секретный ключ для шифрования"; - - // var key = Encoding.ASCII.GetBytes(secret); - // var tokenDescriptor = new SecurityTokenDescriptor - // { - // Issuer = "a", - // Audience = "a", - // Subject = new ClaimsIdentity(claims), - // Expires = DateTime.UtcNow.AddHours(1), - // SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) - // }; - // var tokenHandler = new JwtSecurityTokenHandler(); - // var token = tokenHandler.CreateToken(tokenDescriptor); - // return tokenHandler.WriteToken(token); - //} -} diff --git a/Persistence.IntegrationTests/Controllers/SetpointControllerTest.cs b/Persistence.IntegrationTests/Controllers/SetpointControllerTest.cs index f865ce2..8df4170 100644 --- a/Persistence.IntegrationTests/Controllers/SetpointControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/SetpointControllerTest.cs @@ -17,11 +17,10 @@ namespace Persistence.IntegrationTests.Controllers public SetpointControllerTest(WebAppFactoryFixture factory) : base(factory) { var scope = factory.Services.CreateScope(); - var httpClient = scope.ServiceProvider - .GetRequiredService() - .CreateClient(); + var persistenceClientFactory = scope.ServiceProvider + .GetRequiredService(); - setpointClient = PersistenceClientFactory.GetClient(httpClient); + setpointClient = persistenceClientFactory.GetClient(); } [Fact] diff --git a/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs b/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs index 6c110cf..9b43b8e 100644 --- a/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs @@ -17,11 +17,10 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat dbContext.CleanupDbSet(); var scope = factory.Services.CreateScope(); - var httpClient = scope.ServiceProvider - .GetRequiredService() - .CreateClient(); + var persistenceClientFactory = scope.ServiceProvider + .GetRequiredService(); - timeSeriesClient = PersistenceClientFactory.GetClient>(httpClient); + timeSeriesClient = persistenceClientFactory.GetClient>(); } public async Task InsertRangeSuccess(TDto dto) diff --git a/Persistence.IntegrationTests/JwtToken.cs b/Persistence.IntegrationTests/JwtToken.cs deleted file mode 100644 index 38bf315..0000000 --- a/Persistence.IntegrationTests/JwtToken.cs +++ /dev/null @@ -1,8 +0,0 @@ -using System.Text.Json.Serialization; - -namespace Persistence.IntegrationTests; -public class JwtToken -{ - [JsonPropertyName("access_token")] - public required string AccessToken { get; set; } -} diff --git a/Persistence.IntegrationTests/KeyCloakUser.cs b/Persistence.IntegrationTests/KeyCloakUser.cs deleted file mode 100644 index aa4d335..0000000 --- a/Persistence.IntegrationTests/KeyCloakUser.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Persistence.IntegrationTests; - -/// -/// настройки credentials для пользователя в KeyCloak -/// -public class KeyCloakUser -{ - /// - /// - /// - public required string Username { get; set; } - - /// - /// - /// - public required string Password { get; set; } - - /// - /// - /// - public required string ClientId { get; set; } - - /// - /// - /// - public required string GrantType { get; set; } -} diff --git a/Persistence.IntegrationTests/WebAppFactoryFixture.cs b/Persistence.IntegrationTests/WebAppFactoryFixture.cs index d04509f..b5f6f97 100644 --- a/Persistence.IntegrationTests/WebAppFactoryFixture.cs +++ b/Persistence.IntegrationTests/WebAppFactoryFixture.cs @@ -3,58 +3,34 @@ using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Persistence.API; +using Persistence.Client; using Persistence.Database.Model; using Persistence.Database.Postgres; -using Refit; using RestSharp; -using System.Net.Http.Headers; -using System.Text.Json; -using Persistence.Database.Postgres; -using System.Net.Http.Headers; -using Persistence.Client; -using Microsoft.Extensions.DependencyInjection.Extensions; namespace Persistence.IntegrationTests; public class WebAppFactoryFixture : WebApplicationFactory { - private static readonly JsonSerializerOptions JsonSerializerOptions = new() - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - PropertyNameCaseInsensitive = true, - //Converters = { new ValidationResultConverter() } - }; - - private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions)); - - private readonly string connectionString; - private readonly KeyCloakUser keycloakTestUser; - public readonly string KeycloakGetTokenUrl; - - public WebAppFactoryFixture() - { - var configuration = new ConfigurationBuilder() - .AddJsonFile("appsettings.Tests.json") - .Build(); - - var dbConnection = configuration.GetSection("DbConnection").Get()!; - connectionString = dbConnection.GetConnectionString(); - - keycloakTestUser = configuration.GetSection("KeycloakTestUser").Get()!; - - KeycloakGetTokenUrl = configuration.GetSection("KeycloakGetTokenUrl").Value!; - } + private string connectionString = string.Empty; protected override void ConfigureWebHost(IWebHostBuilder builder) - { - builder.ConfigureServices(services => + { + builder.ConfigureAppConfiguration((hostingContext, config) => + { + config.AddJsonFile("appsettings.Tests.json"); + + var dbConnection = config.Build().GetSection("DbConnection").Get()!; + connectionString = dbConnection.GetConnectionString(); + }); + + builder.ConfigureServices(services => { var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions)); - if (descriptor != null) services.Remove(descriptor); - - services.AddDbContext(options => + services.AddDbContext(options => options.UseNpgsql(connectionString)); services.RemoveAll(); @@ -63,6 +39,8 @@ public class WebAppFactoryFixture : WebApplicationFactory return new TestHttpClientFactory(this); }); + services.AddSingleton(); + var serviceProvider = services.BuildServiceProvider(); using var scope = serviceProvider.CreateScope(); @@ -71,7 +49,7 @@ public class WebAppFactoryFixture : WebApplicationFactory var dbContext = scopedServices.GetRequiredService(); dbContext.Database.EnsureCreatedAndMigrated(); dbContext.SaveChanges(); - }); + }); } public override async ValueTask DisposeAsync() @@ -83,57 +61,4 @@ public class WebAppFactoryFixture : WebApplicationFactory await dbContext.Database.EnsureDeletedAsync(); } - - public T GetHttpClient(string uriSuffix) - { - var httpClient = CreateClient(); - if (string.IsNullOrEmpty(uriSuffix)) - return RestService.For(httpClient, RefitSettings); - - if (httpClient.BaseAddress is not null) - httpClient.BaseAddress = new Uri(httpClient.BaseAddress, uriSuffix); - - return RestService.For(httpClient, RefitSettings); - } - - public async Task GetAuthorizedHttpClient(string uriSuffix) - { - var httpClient = await GetAuthorizedHttpClient(); - if (string.IsNullOrEmpty(uriSuffix)) - return RestService.For(httpClient, RefitSettings); - - if (httpClient.BaseAddress is not null) - httpClient.BaseAddress = new Uri(httpClient.BaseAddress, uriSuffix); - - return RestService.For(httpClient, RefitSettings); - } - - private async Task GetAuthorizedHttpClient() - { - var httpClient = CreateClient(); - var token = await GetTokenAsync(); - httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); - - return httpClient; - } - - private async Task 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(keyCloackResponse.Content)!; - return token.AccessToken; - } - - return String.Empty; - } } diff --git a/Persistence/Models/Configurations/AuthUser.cs b/Persistence/Models/Configurations/AuthUser.cs new file mode 100644 index 0000000..86f11c5 --- /dev/null +++ b/Persistence/Models/Configurations/AuthUser.cs @@ -0,0 +1,12 @@ +namespace Persistence.Models.Configurations; + +/// +/// Настройки credentials для авторизации +/// +public class AuthUser +{ + public required string Username { get; set; } + public required string Password { get; set; } + public required string ClientId { get; set; } + public required string GrantType { get; set; } +} diff --git a/Persistence/Models/Configurations/JwtParams.cs b/Persistence/Models/Configurations/JwtParams.cs new file mode 100644 index 0000000..d8b7b72 --- /dev/null +++ b/Persistence/Models/Configurations/JwtParams.cs @@ -0,0 +1,18 @@ +using System.Text; +using Microsoft.IdentityModel.Tokens; + +namespace Persistence.Models.Configurations +{ + public static class JwtParams + { + private static readonly string KeyValue = "супер секретный ключ для шифрования"; + public static SymmetricSecurityKey SecurityKey + { + get { return new SymmetricSecurityKey(Encoding.ASCII.GetBytes(KeyValue)); } + } + + public static readonly string Issuer = "a"; + + public static readonly string Audience = "a"; + } +} diff --git a/Persistence/Models/Configurations/JwtToken.cs b/Persistence/Models/Configurations/JwtToken.cs new file mode 100644 index 0000000..f787cc3 --- /dev/null +++ b/Persistence/Models/Configurations/JwtToken.cs @@ -0,0 +1,10 @@ +using System.Text.Json.Serialization; + +namespace Persistence.Models.Configurations +{ + public class JwtToken + { + [JsonPropertyName("access_token")] + public required string AccessToken { get; set; } + } +} diff --git a/Persistence/Persistence.csproj b/Persistence/Persistence.csproj index aaccee7..c857356 100644 --- a/Persistence/Persistence.csproj +++ b/Persistence/Persistence.csproj @@ -9,6 +9,7 @@ + From b79d29f08ed633fc3e12212ec3f22431858741d1 Mon Sep 17 00:00:00 2001 From: Roman Efremov Date: Mon, 25 Nov 2024 14:29:42 +0500 Subject: [PATCH 3/3] =?UTF-8?q?=D0=92=D0=BD=D0=B5=D1=81=D1=82=D0=B8=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20=D0=BF=D0=BE=20=D1=80?= =?UTF-8?q?=D0=B5=D0=B7=D1=83=D0=BB=D1=8C=D1=82=D0=B0=D1=82=D0=B0=D0=BC=20?= =?UTF-8?q?=D1=80=D0=B5=D0=B2=D1=8C=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Persistence.API/DependencyInjection.cs | 178 ++++++++++-------- .../PersistenceClientFactory.cs | 4 +- .../TestHttpClientFactory.cs | 3 + 3 files changed, 103 insertions(+), 82 deletions(-) diff --git a/Persistence.API/DependencyInjection.cs b/Persistence.API/DependencyInjection.cs index 2762881..cdfca4c 100644 --- a/Persistence.API/DependencyInjection.cs +++ b/Persistence.API/DependencyInjection.cs @@ -1,14 +1,10 @@ +using System.Text.Json.Nodes; using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Models; -using Persistence.Models; using Persistence.Models.Configurations; -using System.Data.Common; -using System.Text; -using System.Text.Json.Nodes; +using Swashbuckle.AspNetCore.SwaggerGen; namespace Persistence.API; @@ -38,96 +34,47 @@ public static class DependencyInjection c.SwaggerDoc("v1", new OpenApiInfo { Title = "Persistence web api", Version = "v1" }); var needUseKeyCloak = configuration.GetSection("NeedUseKeyCloak").Get(); - if (needUseKeyCloak) - { - c.AddSecurityDefinition("Keycloack", new OpenApiSecurityScheme - { - Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'", - Name = "Authorization", - In = ParameterLocation.Header, - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - Implicit = new OpenApiOAuthFlow - { - AuthorizationUrl = new Uri(configuration["Authentication:AuthorizationUrl"]), - } - } - }); - - c.AddSecurityRequirement(new OpenApiSecurityRequirement() - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "Keycloack" - }, - Scheme = "Bearer", - Name = "Bearer", - In = ParameterLocation.Header, - }, - new List() - } - }); - } - else - { - c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme - { - Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'", - Name = "Authorization", - In = ParameterLocation.Header, - Type = SecuritySchemeType.ApiKey, - Scheme = "Bearer", - }); - - c.AddSecurityRequirement(new OpenApiSecurityRequirement() - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "Bearer" - }, - Scheme = "oauth2", - Name = "Bearer", - In = ParameterLocation.Header, - }, - new List() - } - }); - } + if (needUseKeyCloak) + c.AddKeycloackSecurity(configuration); + else c.AddDefaultSecurity(configuration); //var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; //var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); //var includeControllerXmlComment = true; - //c.IncludeXmlComments(xmlPath, includeControllerXmlComment); - //c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "AsbCloudApp.xml"), includeControllerXmlComment); + //options.IncludeXmlComments(xmlPath, includeControllerXmlComment); + //options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "AsbCloudApp.xml"), includeControllerXmlComment); }); } - public static void AddJWTAuthentication(this IServiceCollection services, IConfiguration configuration) + #region Authentication + public static void AddJWTAuthentication(this IServiceCollection services, IConfiguration configuration) { var needUseKeyCloak = configuration .GetSection("NeedUseKeyCloak") .Get(); - if (needUseKeyCloak) services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) - .AddJwtBearer(options => - { + if (needUseKeyCloak) + services.AddKeyCloakAuthentication(configuration); + else services.AddDefaultAuthentication(configuration); + } + + private static void AddKeyCloakAuthentication(this IServiceCollection services, IConfiguration configuration) + { + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { options.RequireHttpsMetadata = false; options.Audience = configuration["Authentication:Audience"]; options.MetadataAddress = configuration["Authentication:MetadataAddress"]!; options.TokenValidationParameters = new TokenValidationParameters - { - ValidIssuer = configuration["Authentication:ValidIssuer"], - }; - }); - else services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + { + ValidIssuer = configuration["Authentication:ValidIssuer"], + }; + }); + } + + private static void AddDefaultAuthentication(this IServiceCollection services, IConfiguration configuration) + { + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; @@ -176,4 +123,73 @@ public static class DependencyInjection }; }); } + #endregion + + #region Security (Swagger) + private static void AddKeycloackSecurity(this SwaggerGenOptions options, IConfiguration configuration) + { + options.AddSecurityDefinition("Keycloack", new OpenApiSecurityScheme + { + Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'", + Name = "Authorization", + In = ParameterLocation.Header, + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows + { + Implicit = new OpenApiOAuthFlow + { + AuthorizationUrl = new Uri(configuration["Authentication:AuthorizationUrl"]), + } + } + }); + + options.AddSecurityRequirement(new OpenApiSecurityRequirement() + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "Keycloack" + }, + Scheme = "Bearer", + Name = "Bearer", + In = ParameterLocation.Header, + }, + new List() + } + }); + } + + private static void AddDefaultSecurity(this SwaggerGenOptions options, IConfiguration configuration) + { + options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme + { + Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'", + Name = "Authorization", + In = ParameterLocation.Header, + Type = SecuritySchemeType.ApiKey, + Scheme = "Bearer", + }); + + options.AddSecurityRequirement(new OpenApiSecurityRequirement() + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "Bearer" + }, + Scheme = "oauth2", + Name = "Bearer", + In = ParameterLocation.Header, + }, + new List() + } + }); + } + #endregion } diff --git a/Persistence.Client/PersistenceClientFactory.cs b/Persistence.Client/PersistenceClientFactory.cs index 7a8daa8..e84327d 100644 --- a/Persistence.Client/PersistenceClientFactory.cs +++ b/Persistence.Client/PersistenceClientFactory.cs @@ -1,11 +1,13 @@ using System.Text.Json; using Microsoft.Extensions.Configuration; using Persistence.Client.Helpers; -using Persistence.Models.Configurations; using Refit; namespace Persistence.Client { + /// + /// Фабрика клиентов для доступа к Persistence - сервису + /// public class PersistenceClientFactory { private static readonly JsonSerializerOptions JsonSerializerOptions = new() diff --git a/Persistence.IntegrationTests/TestHttpClientFactory.cs b/Persistence.IntegrationTests/TestHttpClientFactory.cs index 1687f49..287498d 100644 --- a/Persistence.IntegrationTests/TestHttpClientFactory.cs +++ b/Persistence.IntegrationTests/TestHttpClientFactory.cs @@ -1,5 +1,8 @@ namespace Persistence.IntegrationTests { + /// + /// Фабрика HTTP клиентов для интеграционных тестов + /// public class TestHttpClientFactory : IHttpClientFactory { private readonly WebAppFactoryFixture factory;