Compare commits
No commits in common. "f5ed62eb7d1e36ebcbe2b870e887a2d389c125fc" and "23e2f869579f67390ac420dbbc325cc57c3a0be9" have entirely different histories.
f5ed62eb7d
...
23e2f86957
@ -1,12 +1,10 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Persistence.Models;
|
||||
using Persistence.Repositories;
|
||||
|
||||
namespace Persistence.API.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
public class SetpointController : ControllerBase, ISetpointApi
|
||||
{
|
||||
|
@ -1,10 +1,8 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi.Any;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Persistence.Models.Configurations;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace Persistence.API;
|
||||
|
||||
@ -32,103 +30,7 @@ public static class DependencyInjection
|
||||
});
|
||||
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Persistence web api", Version = "v1" });
|
||||
|
||||
var needUseKeyCloak = configuration.GetSection("NeedUseKeyCloak").Get<bool>();
|
||||
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;
|
||||
//options.IncludeXmlComments(xmlPath, includeControllerXmlComment);
|
||||
//options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "AsbCloudApp.xml"), includeControllerXmlComment);
|
||||
});
|
||||
}
|
||||
|
||||
#region Authentication
|
||||
public static void AddJWTAuthentication(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var needUseKeyCloak = configuration
|
||||
.GetSection("NeedUseKeyCloak")
|
||||
.Get<bool>();
|
||||
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"],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private static void AddDefaultAuthentication(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
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<AuthUser>()!;
|
||||
|
||||
if (username != keyCloakUser.Username || password != keyCloakUser.Password)
|
||||
{
|
||||
context.Fail("username or password did not match");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Security (Swagger)
|
||||
private static void AddKeycloackSecurity(this SwaggerGenOptions options, IConfiguration configuration)
|
||||
{
|
||||
options.AddSecurityDefinition("Keycloack", new OpenApiSecurityScheme
|
||||
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",
|
||||
@ -143,7 +45,7 @@ public static class DependencyInjection
|
||||
}
|
||||
});
|
||||
|
||||
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
|
||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
|
||||
{
|
||||
{
|
||||
new OpenApiSecurityScheme
|
||||
@ -160,36 +62,27 @@ public static class DependencyInjection
|
||||
new List<string>()
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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<string>()
|
||||
}
|
||||
//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"],
|
||||
};
|
||||
});
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
@ -8,7 +8,7 @@
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true,
|
||||
"applicationUrl": "http://localhost:13616"
|
||||
"applicationUrl": "http://localhost:5032"
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
|
@ -4,6 +4,5 @@
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"NeedUseKeyCloak": false
|
||||
}
|
||||
}
|
||||
|
@ -1,12 +1,11 @@
|
||||
{
|
||||
{
|
||||
"DbConnection": {
|
||||
"Host": "localhost",
|
||||
"Port": 5432,
|
||||
"Username": "postgres",
|
||||
"Password": "q"
|
||||
},
|
||||
"NeedUseKeyCloak": false,
|
||||
"AuthUser": {
|
||||
"KeycloakTestUser": {
|
||||
"username": "myuser",
|
||||
"password": 12345,
|
||||
"clientId": "webapi",
|
||||
|
@ -1,24 +0,0 @@
|
||||
using Persistence.Models;
|
||||
using Refit;
|
||||
|
||||
namespace Persistence.Client.Clients;
|
||||
|
||||
/// <summary>
|
||||
/// Интерфейс для тестирования API, предназначенного для работы с уставками
|
||||
/// </summary>
|
||||
public interface ISetpointClient
|
||||
{
|
||||
private const string BaseRoute = "/api/setpoint";
|
||||
|
||||
[Get($"{BaseRoute}/current")]
|
||||
Task<IApiResponse<IEnumerable<SetpointValueDto>>> GetCurrent([Query(CollectionFormat.Multi)] IEnumerable<Guid> setpointKeys);
|
||||
|
||||
[Get($"{BaseRoute}/history")]
|
||||
Task<IApiResponse<IEnumerable<SetpointValueDto>>> GetHistory([Query(CollectionFormat.Multi)] IEnumerable<Guid> setpointKeys, [Query] DateTimeOffset historyMoment);
|
||||
|
||||
[Get($"{BaseRoute}/log")]
|
||||
Task<IApiResponse<Dictionary<Guid, IEnumerable<SetpointLogDto>>>> GetLog([Query(CollectionFormat.Multi)] IEnumerable<Guid> setpointKeys);
|
||||
|
||||
[Post($"{BaseRoute}/")]
|
||||
Task<IApiResponse> Save(Guid setpointKey, object newValue);
|
||||
}
|
@ -1,72 +0,0 @@
|
||||
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 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);
|
||||
}
|
||||
|
||||
private static string CreateDefaultJwtToken(this AuthUser authUser)
|
||||
{
|
||||
var claims = new List<Claim>()
|
||||
{
|
||||
new("client_id", authUser.ClientId),
|
||||
new("username", authUser.Username),
|
||||
new("password", authUser.Password),
|
||||
new("grant_type", authUser.GrantType)
|
||||
};
|
||||
|
||||
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 keyCloackResponse = restClient.Post(request);
|
||||
if (keyCloackResponse.IsSuccessful && !String.IsNullOrEmpty(keyCloackResponse.Content))
|
||||
{
|
||||
var token = JsonSerializer.Deserialize<JwtToken>(keyCloackResponse.Content)!;
|
||||
return token.AccessToken;
|
||||
}
|
||||
|
||||
return String.Empty;
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.2.1" />
|
||||
<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.IdentityModel.Tokens.Jwt" Version="8.2.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Persistence\Persistence.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Models\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -1,32 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Persistence.Client.Helpers;
|
||||
using Refit;
|
||||
|
||||
namespace Persistence.Client
|
||||
{
|
||||
/// <summary>
|
||||
/// Фабрика клиентов для доступа к Persistence - сервису
|
||||
/// </summary>
|
||||
public class PersistenceClientFactory
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonSerializerOptions = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
|
||||
private HttpClient httpClient;
|
||||
public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IConfiguration configuration)
|
||||
{
|
||||
this.httpClient = httpClientFactory.CreateClient();
|
||||
|
||||
httpClient.Authorize(configuration);
|
||||
}
|
||||
|
||||
public T GetClient<T>()
|
||||
{
|
||||
return RestService.For<T>(httpClient, RefitSettings);
|
||||
}
|
||||
}
|
||||
}
|
43
Persistence.IntegrationTests/ApiTokenHelper.cs
Normal file
43
Persistence.IntegrationTests/ApiTokenHelper.cs
Normal file
@ -0,0 +1,43 @@
|
||||
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<string> roles)
|
||||
//{
|
||||
// var claims = new List<Claim>
|
||||
// {
|
||||
// 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);
|
||||
//}
|
||||
}
|
25
Persistence.IntegrationTests/Clients/ISetpointClient.cs
Normal file
25
Persistence.IntegrationTests/Clients/ISetpointClient.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using Persistence.Models;
|
||||
using Refit;
|
||||
|
||||
namespace Persistence.IntegrationTests.Clients
|
||||
{
|
||||
/// <summary>
|
||||
/// Интерфейс для тестирования API, предназначенного для работы с уставками
|
||||
/// </summary>
|
||||
public interface ISetpointClient
|
||||
{
|
||||
private const string BaseRoute = "/api/setpoint";
|
||||
|
||||
[Get($"{BaseRoute}/current")]
|
||||
Task<IApiResponse<IEnumerable<SetpointValueDto>>> GetCurrent([Query(CollectionFormat.Multi)] IEnumerable<Guid> setpointKeys);
|
||||
|
||||
[Get($"{BaseRoute}/history")]
|
||||
Task<IApiResponse<IEnumerable<SetpointValueDto>>> GetHistory([Query(CollectionFormat.Multi)] IEnumerable<Guid> setpointKeys, [Query] DateTimeOffset historyMoment);
|
||||
|
||||
[Get($"{BaseRoute}/log")]
|
||||
Task<IApiResponse<Dictionary<Guid, IEnumerable<SetpointLogDto>>>> GetLog([Query(CollectionFormat.Multi)] IEnumerable<Guid> setpointKeys);
|
||||
|
||||
[Post($"{BaseRoute}/")]
|
||||
Task<IApiResponse> Save(Guid setpointKey, object newValue);
|
||||
}
|
||||
}
|
@ -2,7 +2,7 @@
|
||||
using Persistence.Models;
|
||||
using Refit;
|
||||
|
||||
namespace Persistence.Client.Clients;
|
||||
namespace Persistence.IntegrationTests.Clients;
|
||||
public interface ITimeSeriesClient<TDto>
|
||||
where TDto : class, new()
|
||||
{
|
@ -1,5 +1,4 @@
|
||||
using Persistence.Client;
|
||||
using Persistence.Database.Model;
|
||||
using Persistence.Database.Model;
|
||||
using Persistence.Repository.Data;
|
||||
using Xunit;
|
||||
|
||||
|
@ -1,14 +1,12 @@
|
||||
using System.Net;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Persistence.Client;
|
||||
using Persistence.Client.Clients;
|
||||
using Persistence.IntegrationTests.Clients;
|
||||
using Xunit;
|
||||
|
||||
namespace Persistence.IntegrationTests.Controllers
|
||||
{
|
||||
public class SetpointControllerTest : BaseIntegrationTest
|
||||
{
|
||||
private ISetpointClient setpointClient;
|
||||
private ISetpointClient client;
|
||||
private class TestObject
|
||||
{
|
||||
public string? value1 { get; set; }
|
||||
@ -16,11 +14,7 @@ namespace Persistence.IntegrationTests.Controllers
|
||||
}
|
||||
public SetpointControllerTest(WebAppFactoryFixture factory) : base(factory)
|
||||
{
|
||||
var scope = factory.Services.CreateScope();
|
||||
var persistenceClientFactory = scope.ServiceProvider
|
||||
.GetRequiredService<PersistenceClientFactory>();
|
||||
|
||||
setpointClient = persistenceClientFactory.GetClient<ISetpointClient>();
|
||||
client = factory.GetHttpClient<ISetpointClient>(string.Empty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@ -34,7 +28,7 @@ namespace Persistence.IntegrationTests.Controllers
|
||||
};
|
||||
|
||||
//act
|
||||
var response = await setpointClient.GetCurrent(setpointKeys);
|
||||
var response = await client.GetCurrent(setpointKeys);
|
||||
|
||||
//assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
@ -49,7 +43,7 @@ namespace Persistence.IntegrationTests.Controllers
|
||||
var setpointKey = await Save();
|
||||
|
||||
//act
|
||||
var response = await setpointClient.GetCurrent([setpointKey]);
|
||||
var response = await client.GetCurrent([setpointKey]);
|
||||
|
||||
//assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
@ -70,7 +64,7 @@ namespace Persistence.IntegrationTests.Controllers
|
||||
var historyMoment = DateTimeOffset.UtcNow;
|
||||
|
||||
//act
|
||||
var response = await setpointClient.GetHistory(setpointKeys, historyMoment);
|
||||
var response = await client.GetHistory(setpointKeys, historyMoment);
|
||||
|
||||
//assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
@ -87,7 +81,7 @@ namespace Persistence.IntegrationTests.Controllers
|
||||
historyMoment = historyMoment.AddDays(1);
|
||||
|
||||
//act
|
||||
var response = await setpointClient.GetHistory([setpointKey], historyMoment);
|
||||
var response = await client.GetHistory([setpointKey], historyMoment);
|
||||
|
||||
//assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
@ -107,7 +101,7 @@ namespace Persistence.IntegrationTests.Controllers
|
||||
};
|
||||
|
||||
//act
|
||||
var response = await setpointClient.GetLog(setpointKeys);
|
||||
var response = await client.GetLog(setpointKeys);
|
||||
|
||||
//assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
@ -122,7 +116,7 @@ namespace Persistence.IntegrationTests.Controllers
|
||||
var setpointKey = await Save();
|
||||
|
||||
//act
|
||||
var response = await setpointClient.GetLog([setpointKey]);
|
||||
var response = await client.GetLog([setpointKey]);
|
||||
|
||||
//assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
@ -148,7 +142,7 @@ namespace Persistence.IntegrationTests.Controllers
|
||||
};
|
||||
|
||||
//act
|
||||
var response = await setpointClient.Save(setpointKey, setpointValue);
|
||||
var response = await client.Save(setpointKey, setpointValue);
|
||||
|
||||
//assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
@ -1,9 +1,7 @@
|
||||
using System.Net;
|
||||
using Mapster;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Persistence.Client;
|
||||
using Persistence.Client.Clients;
|
||||
using Mapster;
|
||||
using Persistence.Database.Model;
|
||||
using Persistence.IntegrationTests.Clients;
|
||||
using System.Net;
|
||||
using Xunit;
|
||||
|
||||
namespace Persistence.IntegrationTests.Controllers;
|
||||
@ -11,17 +9,16 @@ public abstract class TimeSeriesBaseControllerTest<TEntity, TDto> : BaseIntegrat
|
||||
where TEntity : class, ITimestampedData, new()
|
||||
where TDto : class, new()
|
||||
{
|
||||
private ITimeSeriesClient<TDto> timeSeriesClient;
|
||||
private ITimeSeriesClient<TDto> client;
|
||||
|
||||
public TimeSeriesBaseControllerTest(WebAppFactoryFixture factory) : base(factory)
|
||||
{
|
||||
dbContext.CleanupDbSet<TEntity>();
|
||||
|
||||
var scope = factory.Services.CreateScope();
|
||||
var persistenceClientFactory = scope.ServiceProvider
|
||||
.GetRequiredService<PersistenceClientFactory>();
|
||||
|
||||
timeSeriesClient = persistenceClientFactory.GetClient<ITimeSeriesClient<TDto>>();
|
||||
Task.Run(async () =>
|
||||
{
|
||||
client = await factory.GetAuthorizedHttpClient<ITimeSeriesClient<TDto>>(string.Empty);
|
||||
}).Wait();
|
||||
}
|
||||
|
||||
public async Task InsertRangeSuccess(TDto dto)
|
||||
@ -30,7 +27,7 @@ public abstract class TimeSeriesBaseControllerTest<TEntity, TDto> : BaseIntegrat
|
||||
var expected = dto.Adapt<TDto>();
|
||||
|
||||
//act
|
||||
var response = await timeSeriesClient.InsertRange(new TDto[] { expected });
|
||||
var response = await client.InsertRange(new TDto[] { expected });
|
||||
|
||||
//assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
@ -46,7 +43,7 @@ public abstract class TimeSeriesBaseControllerTest<TEntity, TDto> : BaseIntegrat
|
||||
|
||||
dbContext.SaveChanges();
|
||||
|
||||
var response = await timeSeriesClient.Get(beginDate, endDate);
|
||||
var response = await client.Get(beginDate, endDate);
|
||||
|
||||
//assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
@ -68,7 +65,7 @@ public abstract class TimeSeriesBaseControllerTest<TEntity, TDto> : BaseIntegrat
|
||||
|
||||
dbContext.SaveChanges();
|
||||
|
||||
var response = await timeSeriesClient.GetDatesRange();
|
||||
var response = await client.GetDatesRange();
|
||||
|
||||
//assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
@ -98,7 +95,7 @@ public abstract class TimeSeriesBaseControllerTest<TEntity, TDto> : BaseIntegrat
|
||||
|
||||
dbContext.SaveChanges();
|
||||
|
||||
var response = await timeSeriesClient.GetResampledData(entity.Date.AddMinutes(-1), differenceBetweenStartAndEndDays * 24 * 60 * 60 + 60, approxPointsCount);
|
||||
var response = await client.GetResampledData(entity.Date.AddMinutes(-1), differenceBetweenStartAndEndDays * 24 * 60 * 60 + 60, approxPointsCount);
|
||||
|
||||
//assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
8
Persistence.IntegrationTests/JwtToken.cs
Normal file
8
Persistence.IntegrationTests/JwtToken.cs
Normal 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; }
|
||||
}
|
27
Persistence.IntegrationTests/KeyCloakUser.cs
Normal file
27
Persistence.IntegrationTests/KeyCloakUser.cs
Normal 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; }
|
||||
}
|
@ -25,7 +25,6 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Persistence.API\Persistence.API.csproj" />
|
||||
<ProjectReference Include="..\Persistence.Client\Persistence.Client.csproj" />
|
||||
<ProjectReference Include="..\Persistence.Database.Postgres\Persistence.Database.Postgres.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
@ -1,19 +0,0 @@
|
||||
namespace Persistence.IntegrationTests
|
||||
{
|
||||
/// <summary>
|
||||
/// Фабрика HTTP клиентов для интеграционных тестов
|
||||
/// </summary>
|
||||
public class TestHttpClientFactory : IHttpClientFactory
|
||||
{
|
||||
private readonly WebAppFactoryFixture factory;
|
||||
|
||||
public TestHttpClientFactory(WebAppFactoryFixture factory)
|
||||
{
|
||||
this.factory = factory;
|
||||
}
|
||||
public HttpClient CreateClient(string name)
|
||||
{
|
||||
return factory.CreateClient();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,52 +1,65 @@
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
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;
|
||||
|
||||
namespace Persistence.IntegrationTests;
|
||||
public class WebAppFactoryFixture : WebApplicationFactory<Startup>
|
||||
{
|
||||
private string connectionString = string.Empty;
|
||||
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<DbConnection>()!;
|
||||
connectionString = dbConnection.GetConnectionString();
|
||||
|
||||
keycloakTestUser = configuration.GetSection("KeycloakTestUser").Get<KeyCloakUser>()!;
|
||||
|
||||
KeycloakGetTokenUrl = configuration.GetSection("KeycloakGetTokenUrl").Value!;
|
||||
}
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureAppConfiguration((hostingContext, config) =>
|
||||
{
|
||||
config.AddJsonFile("appsettings.Tests.json");
|
||||
|
||||
var dbConnection = config.Build().GetSection("DbConnection").Get<DbConnection>()!;
|
||||
connectionString = dbConnection.GetConnectionString();
|
||||
});
|
||||
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<PersistenceDbContext>));
|
||||
|
||||
if (descriptor != null)
|
||||
services.Remove(descriptor);
|
||||
|
||||
services.AddDbContext<PersistenceDbContext>(options =>
|
||||
options.UseNpgsql(connectionString));
|
||||
|
||||
services.RemoveAll<IHttpClientFactory>();
|
||||
services.AddSingleton<IHttpClientFactory>(provider =>
|
||||
{
|
||||
return new TestHttpClientFactory(this);
|
||||
});
|
||||
|
||||
services.AddSingleton<PersistenceClientFactory>();
|
||||
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
using var scope = serviceProvider.CreateScope();
|
||||
var scopedServices = scope.ServiceProvider;
|
||||
|
||||
var dbContext = scopedServices.GetRequiredService<PersistenceDbContext>();
|
||||
|
||||
dbContext.Database.EnsureCreatedAndMigrated();
|
||||
dbContext.SaveChanges();
|
||||
});
|
||||
@ -61,4 +74,57 @@ public class WebAppFactoryFixture : WebApplicationFactory<Startup>
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
@ -13,9 +13,7 @@ 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("{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}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Persistence.Database.Postgres", "Persistence.Database.Postgres\Persistence.Database.Postgres.csproj", "{CC284D27-162D-490C-B6CF-74D666B7C5F3}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@ -47,10 +45,6 @@ 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
|
||||
|
@ -1,12 +0,0 @@
|
||||
namespace Persistence.Models.Configurations;
|
||||
|
||||
/// <summary>
|
||||
/// Настройки credentials для авторизации
|
||||
/// </summary>
|
||||
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; }
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
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";
|
||||
}
|
||||
}
|
@ -1,10 +0,0 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Persistence.Models.Configurations
|
||||
{
|
||||
public class JwtToken
|
||||
{
|
||||
[JsonPropertyName("access_token")]
|
||||
public required string AccessToken { get; set; }
|
||||
}
|
||||
}
|
@ -9,7 +9,6 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.10" />
|
||||
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.2.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
Loading…
Reference in New Issue
Block a user