Remove references to Managing.Aspire.AppHost and Managing.Aspire.ServiceDefaults from solution and project files; update API project to eliminate unused references and adjust JWT token handling in Program.cs; enhance NSwag generation for Axios and Fetch clients, including new import handling.

This commit is contained in:
2025-12-14 00:18:02 +07:00
parent 0126377486
commit 2157d1f2c9
5 changed files with 72 additions and 49 deletions

View File

@@ -39,7 +39,6 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Managing.Bootstrap\Managing.Bootstrap.csproj"/> <ProjectReference Include="..\Managing.Bootstrap\Managing.Bootstrap.csproj"/>
<ProjectReference Include="..\Managing.Aspire.ServiceDefaults\Managing.Aspire.ServiceDefaults.csproj"/>
<ProjectReference Include="..\Managing.Core\Managing.Core.csproj"/> <ProjectReference Include="..\Managing.Core\Managing.Core.csproj"/>
</ItemGroup> </ItemGroup>

View File

@@ -70,8 +70,6 @@ SentrySdk.Init(options =>
options.Environment = builder.Environment.EnvironmentName; options.Environment = builder.Environment.EnvironmentName;
}); });
// Add Service Defaults - using extension methods directly
builder.Services.AddServiceDiscovery();
builder.Services.AddHealthChecks() builder.Services.AddHealthChecks()
.AddCheck("self", () => HealthCheckResult.Healthy(), ["api"]); .AddCheck("self", () => HealthCheckResult.Healthy(), ["api"]);
@@ -167,7 +165,9 @@ builder.Host.UseSerilog((hostBuilder, loggerConfiguration) =>
}; };
loggerConfiguration loggerConfiguration
.MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", LogEventLevel.Warning) // Filter out EF Core SQL query logs .MinimumLevel
.Override("Microsoft.EntityFrameworkCore.Database.Command",
LogEventLevel.Warning) // Filter out EF Core SQL query logs
.WriteTo.Console() .WriteTo.Console()
.WriteTo.Elasticsearch(es); .WriteTo.Elasticsearch(es);
}); });
@@ -225,9 +225,9 @@ var validAudiences = builder.Configuration.GetSection("Authentication:Schemes:Be
.Get<string[]>() ?? Array.Empty<string>(); .Get<string[]>() ?? Array.Empty<string>();
// Determine if validation should be enabled (enable in production, allow override via config) // Determine if validation should be enabled (enable in production, allow override via config)
var enableIssuerValidation = builder.Configuration.GetValue<bool>("Jwt:ValidateIssuer", var enableIssuerValidation = builder.Configuration.GetValue<bool>("Jwt:ValidateIssuer",
!builder.Environment.IsDevelopment()); !builder.Environment.IsDevelopment());
var enableAudienceValidation = builder.Configuration.GetValue<bool>("Jwt:ValidateAudience", var enableAudienceValidation = builder.Configuration.GetValue<bool>("Jwt:ValidateAudience",
!builder.Environment.IsDevelopment()); !builder.Environment.IsDevelopment());
// Configure clock skew (tolerance for time differences between servers) // Configure clock skew (tolerance for time differences between servers)
@@ -268,7 +268,7 @@ builder.Services
context.Token = null; context.Token = null;
return Task.CompletedTask; return Task.CompletedTask;
} }
// Handle tokens sent without "Bearer " prefix for authenticated endpoints // Handle tokens sent without "Bearer " prefix for authenticated endpoints
// The standard middleware expects "Bearer <token>" but some clients send just the token // The standard middleware expects "Bearer <token>" but some clients send just the token
if (string.IsNullOrEmpty(context.Token)) if (string.IsNullOrEmpty(context.Token))
@@ -284,7 +284,7 @@ builder.Services
// Otherwise, let the default middleware extract it (it will strip "Bearer " automatically) // Otherwise, let the default middleware extract it (it will strip "Bearer " automatically)
} }
} }
// If you want to get the token from a custom header or query string // If you want to get the token from a custom header or query string
// var accessToken = context.Request.Query["access_token"]; // var accessToken = context.Request.Query["access_token"];
// if (!string.IsNullOrEmpty(accessToken) && // if (!string.IsNullOrEmpty(accessToken) &&
@@ -298,30 +298,30 @@ builder.Services
{ {
var logger = context.HttpContext.RequestServices var logger = context.HttpContext.RequestServices
.GetService<ILogger<Program>>(); .GetService<ILogger<Program>>();
// Check if the endpoint allows anonymous access // Check if the endpoint allows anonymous access
var endpoint = context.HttpContext.GetEndpoint(); var endpoint = context.HttpContext.GetEndpoint();
var allowAnonymous = endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null; var allowAnonymous = endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null;
// For anonymous endpoints with malformed tokens, skip authentication instead of failing // For anonymous endpoints with malformed tokens, skip authentication instead of failing
if (allowAnonymous && context.Exception is SecurityTokenMalformedException) if (allowAnonymous && context.Exception is SecurityTokenMalformedException)
{ {
logger?.LogDebug("Skipping malformed token validation for anonymous endpoint: {Path}", logger?.LogDebug("Skipping malformed token validation for anonymous endpoint: {Path}",
context.Request.Path); context.Request.Path);
context.NoResult(); // Skip authentication, don't fail context.NoResult(); // Skip authentication, don't fail
return Task.CompletedTask; return Task.CompletedTask;
} }
if (context.Exception is SecurityTokenExpiredException) if (context.Exception is SecurityTokenExpiredException)
{ {
context.Response.Headers["Token-Expired"] = "true"; context.Response.Headers["Token-Expired"] = "true";
logger?.LogWarning("JWT token expired for request: {Path}", logger?.LogWarning("JWT token expired for request: {Path}",
context.Request.Path); context.Request.Path);
} }
else else
{ {
logger?.LogError(context.Exception, logger?.LogError(context.Exception,
"JWT authentication failed for request: {Path}", "JWT authentication failed for request: {Path}",
context.Request.Path); context.Request.Path);
} }
@@ -332,12 +332,12 @@ builder.Services
{ {
var logger = context.HttpContext.RequestServices var logger = context.HttpContext.RequestServices
.GetService<ILogger<Program>>(); .GetService<ILogger<Program>>();
try try
{ {
var userService = context.HttpContext.RequestServices var userService = context.HttpContext.RequestServices
.GetRequiredService<IUserService>(); .GetRequiredService<IUserService>();
// JWT token contains 'address' claim (not NameIdentifier) // JWT token contains 'address' claim (not NameIdentifier)
var address = context.Principal.FindFirst("address")?.Value; var address = context.Principal.FindFirst("address")?.Value;
@@ -354,7 +354,7 @@ builder.Services
else else
{ {
logger?.LogWarning( logger?.LogWarning(
"JWT token validated but user not found for address: {Address}", "JWT token validated but user not found for address: {Address}",
address); address);
context.Fail("User not found"); context.Fail("User not found");
} }
@@ -367,7 +367,7 @@ builder.Services
} }
catch (Exception ex) catch (Exception ex)
{ {
logger?.LogError(ex, logger?.LogError(ex,
"Error during JWT token validation - user lookup failed"); "Error during JWT token validation - user lookup failed");
context.Fail("Authentication failed: user lookup error"); context.Fail("Authentication failed: user lookup error");
} }
@@ -482,19 +482,19 @@ app.Use(async (context, next) =>
context.Response.Headers.Append("X-XSS-Protection", "1; mode=block"); context.Response.Headers.Append("X-XSS-Protection", "1; mode=block");
context.Response.Headers.Append("Referrer-Policy", "strict-origin-when-cross-origin"); context.Response.Headers.Append("Referrer-Policy", "strict-origin-when-cross-origin");
context.Response.Headers.Append("Permissions-Policy", "geolocation=(), microphone=(), camera=()"); context.Response.Headers.Append("Permissions-Policy", "geolocation=(), microphone=(), camera=()");
// Content Security Policy - only for non-Swagger endpoints // Content Security Policy - only for non-Swagger endpoints
if (!context.Request.Path.StartsWithSegments("/swagger") && if (!context.Request.Path.StartsWithSegments("/swagger") &&
!context.Request.Path.StartsWithSegments("/health") && !context.Request.Path.StartsWithSegments("/health") &&
!context.Request.Path.StartsWithSegments("/alive")) !context.Request.Path.StartsWithSegments("/alive"))
{ {
context.Response.Headers.Append("Content-Security-Policy", context.Response.Headers.Append("Content-Security-Policy",
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:;"); "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:;");
} }
// Remove server header (optional - Kestrel can be configured separately) // Remove server header (optional - Kestrel can be configured separately)
context.Response.Headers.Remove("Server"); context.Response.Headers.Remove("Server");
await next(); await next();
}); });

View File

@@ -29,6 +29,9 @@ Directory.CreateDirectory(targetWebAppDirectory); // Ensure the directory exists
var targetWeb3ProxyDirectory = Path.Combine(solutionDirectory, "src", "Managing.Web3Proxy", "src", "generated"); var targetWeb3ProxyDirectory = Path.Combine(solutionDirectory, "src", "Managing.Web3Proxy", "src", "generated");
Directory.CreateDirectory(targetWeb3ProxyDirectory); Directory.CreateDirectory(targetWeb3ProxyDirectory);
var targetKaigenWebDirectory = "/Users/oda/Desktop/Projects/kaigen-web/webapp/src/generated";
Directory.CreateDirectory(targetKaigenWebDirectory);
var settings = new TypeScriptClientGeneratorSettings var settings = new TypeScriptClientGeneratorSettings
{ {
ClassName = "{controller}Client", ClassName = "{controller}Client",
@@ -53,13 +56,38 @@ var settings = new TypeScriptClientGeneratorSettings
var generatorApiClient = new TypeScriptClientGenerator(document, settings); var generatorApiClient = new TypeScriptClientGenerator(document, settings);
var codeApiClient = generatorApiClient.GenerateFile(); var codeApiClient = generatorApiClient.GenerateFile();
// Add the necessary imports after the auto-generated comment // Settings for Kaigen web project using Axios
var settingsAxios = new TypeScriptClientGeneratorSettings
{
ClassName = "{controller}Client",
ClientBaseClass = "AuthorizedApiBase",
ConfigurationClass = "IConfig",
GenerateDtoTypes = true,
UseTransformOptionsMethod = true,
TypeScriptGeneratorSettings =
{
EnumStyle = TypeScriptEnumStyle.Enum,
DateTimeType = TypeScriptDateTimeType.Date,
NullValue = TypeScriptNullValue.Null,
TypeStyle = TypeScriptTypeStyle.Interface,
GenerateDefaultValues = true,
MarkOptionalProperties = true,
TypeScriptVersion = 4.3m
},
OperationNameGenerator = new MultipleClientsFromFirstTagAndOperationIdGenerator(),
Template = TypeScriptTemplate.Axios,
};
var generatorApiClientAxios = new TypeScriptClientGenerator(document, settingsAxios);
var codeApiClientAxios = generatorApiClientAxios.GenerateFile();
// Add the necessary imports after the auto-generated comment for Fetch version
var requiredImports = @" var requiredImports = @"
import AuthorizedApiBase from ""./AuthorizedApiBase""; import AuthorizedApiBase from ""./AuthorizedApiBase"";
import IConfig from ""./IConfig""; import IConfig from ""./IConfig"";
"; ";
// Find the end of the auto-generated comment and insert imports // Find the end of the auto-generated comment and insert imports for Fetch version
var autoGeneratedEndIndex = codeApiClient.IndexOf("//----------------------"); var autoGeneratedEndIndex = codeApiClient.IndexOf("//----------------------");
if (autoGeneratedEndIndex != -1) if (autoGeneratedEndIndex != -1)
{ {
@@ -72,7 +100,21 @@ if (autoGeneratedEndIndex != -1)
} }
} }
// Add the necessary imports for Axios version as well
var autoGeneratedEndIndexAxios = codeApiClientAxios.IndexOf("//----------------------");
if (autoGeneratedEndIndexAxios != -1)
{
// Find the second occurrence (end of the comment block)
autoGeneratedEndIndexAxios = codeApiClientAxios.IndexOf("//----------------------", autoGeneratedEndIndexAxios + 1);
if (autoGeneratedEndIndexAxios != -1)
{
autoGeneratedEndIndexAxios = codeApiClientAxios.IndexOf("\n", autoGeneratedEndIndexAxios) + 1;
codeApiClientAxios = codeApiClientAxios.Insert(autoGeneratedEndIndexAxios, requiredImports);
}
}
File.WriteAllText(Path.Combine(targetWebAppDirectory, "ManagingApi.ts"), codeApiClient); File.WriteAllText(Path.Combine(targetWebAppDirectory, "ManagingApi.ts"), codeApiClient);
File.WriteAllText(Path.Combine(targetKaigenWebDirectory, "ManagingApi.ts"), codeApiClientAxios);
var settingsTypes = new TypeScriptClientGeneratorSettings var settingsTypes = new TypeScriptClientGeneratorSettings
{ {
@@ -97,4 +139,5 @@ var generatorTypes = new TypeScriptClientGenerator(document, settingsTypes);
var codeTypes = generatorTypes.GenerateFile(); var codeTypes = generatorTypes.GenerateFile();
File.WriteAllText(Path.Combine(targetWebAppDirectory, "ManagingApiTypes.ts"), codeTypes); File.WriteAllText(Path.Combine(targetWebAppDirectory, "ManagingApiTypes.ts"), codeTypes);
File.WriteAllText(Path.Combine(targetWeb3ProxyDirectory, "ManagingApiTypes.ts"), codeTypes); File.WriteAllText(Path.Combine(targetWeb3ProxyDirectory, "ManagingApiTypes.ts"), codeTypes);
File.WriteAllText(Path.Combine(targetKaigenWebDirectory, "ManagingApiTypes.ts"), codeTypes);

View File

@@ -4,9 +4,10 @@
* API clients inherit from #AuthorizedApiBase and provide the config. * API clients inherit from #AuthorizedApiBase and provide the config.
*/ */
import { Cookies } from 'react-cookie' import {Cookies} from 'react-cookie'
import type IConfig from './IConfig' import type IConfig from './IConfig'
export default class AuthorizedApiBase { export default class AuthorizedApiBase {
private readonly config: IConfig private readonly config: IConfig
@@ -14,7 +15,7 @@ export default class AuthorizedApiBase {
this.config = config this.config = config
} }
transformOptions = (options: any): Promise<RequestInit> => { transformOptions = (options: any): Promise<any> => {
const cookies = new Cookies() const cookies = new Cookies()
const bearerToken = cookies.get('token') const bearerToken = cookies.get('token')
if (bearerToken) { if (bearerToken) {

View File

@@ -62,10 +62,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Managing.ABI.GmxV2", "Managing.ABI.GmxV2\Managing.ABI.GmxV2.csproj", "{4521E1A9-AF81-4CA8-8B4D-30C261ECE977}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Managing.ABI.GmxV2", "Managing.ABI.GmxV2\Managing.ABI.GmxV2.csproj", "{4521E1A9-AF81-4CA8-8B4D-30C261ECE977}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Managing.Aspire.AppHost", "Managing.Aspire.AppHost\Managing.Aspire.AppHost.csproj", "{2A7AC5A7-B4D6-4DF2-976B-6EE771BB4C31}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Managing.Aspire.ServiceDefaults", "Managing.Aspire.ServiceDefaults\Managing.Aspire.ServiceDefaults.csproj", "{F58949B8-4173-4F9E-83FF-B88FA2C5C849}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Managing.Nswag", "Managing.Nswag\Managing.Nswag.csproj", "{BE50F950-C1D4-4CE0-B32E-6AAC996770D5}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Managing.Nswag", "Managing.Nswag\Managing.Nswag.csproj", "{BE50F950-C1D4-4CE0-B32E-6AAC996770D5}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Managing.Workers", "Managing.Workers\Managing.Workers.csproj", "{B7D66A73-CA3A-4DE5-8E88-59D50C4018A6}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Managing.Workers", "Managing.Workers\Managing.Workers.csproj", "{B7D66A73-CA3A-4DE5-8E88-59D50C4018A6}"
@@ -218,22 +214,6 @@ Global
{4521E1A9-AF81-4CA8-8B4D-30C261ECE977}.Release|Any CPU.Build.0 = Release|Any CPU {4521E1A9-AF81-4CA8-8B4D-30C261ECE977}.Release|Any CPU.Build.0 = Release|Any CPU
{4521E1A9-AF81-4CA8-8B4D-30C261ECE977}.Release|x64.ActiveCfg = Release|Any CPU {4521E1A9-AF81-4CA8-8B4D-30C261ECE977}.Release|x64.ActiveCfg = Release|Any CPU
{4521E1A9-AF81-4CA8-8B4D-30C261ECE977}.Release|x64.Build.0 = Release|Any CPU {4521E1A9-AF81-4CA8-8B4D-30C261ECE977}.Release|x64.Build.0 = Release|Any CPU
{2A7AC5A7-B4D6-4DF2-976B-6EE771BB4C31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2A7AC5A7-B4D6-4DF2-976B-6EE771BB4C31}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2A7AC5A7-B4D6-4DF2-976B-6EE771BB4C31}.Debug|x64.ActiveCfg = Debug|Any CPU
{2A7AC5A7-B4D6-4DF2-976B-6EE771BB4C31}.Debug|x64.Build.0 = Debug|Any CPU
{2A7AC5A7-B4D6-4DF2-976B-6EE771BB4C31}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2A7AC5A7-B4D6-4DF2-976B-6EE771BB4C31}.Release|Any CPU.Build.0 = Release|Any CPU
{2A7AC5A7-B4D6-4DF2-976B-6EE771BB4C31}.Release|x64.ActiveCfg = Release|Any CPU
{2A7AC5A7-B4D6-4DF2-976B-6EE771BB4C31}.Release|x64.Build.0 = Release|Any CPU
{F58949B8-4173-4F9E-83FF-B88FA2C5C849}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F58949B8-4173-4F9E-83FF-B88FA2C5C849}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F58949B8-4173-4F9E-83FF-B88FA2C5C849}.Debug|x64.ActiveCfg = Debug|Any CPU
{F58949B8-4173-4F9E-83FF-B88FA2C5C849}.Debug|x64.Build.0 = Debug|Any CPU
{F58949B8-4173-4F9E-83FF-B88FA2C5C849}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F58949B8-4173-4F9E-83FF-B88FA2C5C849}.Release|Any CPU.Build.0 = Release|Any CPU
{F58949B8-4173-4F9E-83FF-B88FA2C5C849}.Release|x64.ActiveCfg = Release|Any CPU
{F58949B8-4173-4F9E-83FF-B88FA2C5C849}.Release|x64.Build.0 = Release|Any CPU
{BE50F950-C1D4-4CE0-B32E-6AAC996770D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BE50F950-C1D4-4CE0-B32E-6AAC996770D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BE50F950-C1D4-4CE0-B32E-6AAC996770D5}.Debug|Any CPU.Build.0 = Debug|Any CPU {BE50F950-C1D4-4CE0-B32E-6AAC996770D5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BE50F950-C1D4-4CE0-B32E-6AAC996770D5}.Debug|x64.ActiveCfg = Debug|Any CPU {BE50F950-C1D4-4CE0-B32E-6AAC996770D5}.Debug|x64.ActiveCfg = Debug|Any CPU