refactor: enhance JWT authentication and CORS configuration

Updated JWT authentication to use configuration values instead of hardcoded secrets, improving security and flexibility. Enhanced CORS policy to conditionally allow origins based on configuration settings, with logging for permissive defaults. Updated README to reflect project renaming and clarify service context.
This commit is contained in:
Oleksandr Bezdieniezhnykh
2026-05-14 19:48:25 +03:00
parent 2fe394d732
commit 7025f4d075
74 changed files with 8494 additions and 19 deletions
+27
View File
@@ -0,0 +1,27 @@
namespace Azaion.Flights.Infrastructure;
public static class ConfigurationResolver
{
// Fail-fast contract: missing or whitespace-only values throw at startup so a
// production deploy without the operator-confirmed values cannot silently
// accept an insecure default (e.g. a development JWT secret, a localhost DB).
public static string ResolveRequiredOrThrow(
IConfiguration configuration,
string envVar,
string configKey,
string humanLabel)
{
ArgumentNullException.ThrowIfNull(configuration);
var value = Environment.GetEnvironmentVariable(envVar);
if (string.IsNullOrWhiteSpace(value))
value = configuration[configKey];
if (string.IsNullOrWhiteSpace(value))
throw new InvalidOperationException(
$"{humanLabel} is not configured. Set the {envVar} environment variable " +
$"or the {configKey} configuration key.");
return value;
}
}
@@ -0,0 +1,41 @@
namespace Azaion.Flights.Infrastructure;
public static class CorsConfigurationValidator
{
public const string MissingOriginsMessage =
"CORS is misconfigured: CorsConfig:AllowedOrigins is empty and CorsConfig:AllowAnyOrigin is not true. " +
"Refusing to start in Production with a permissive CORS policy. " +
"Set CorsConfig:AllowedOrigins to a non-empty array, or set CorsConfig:AllowAnyOrigin=true to opt in.";
public const string PermissiveDefaultWarning =
"CorsConfig:AllowedOrigins is empty and CorsConfig:AllowAnyOrigin is not true. " +
"Permissive CORS is being applied for environment {Environment}; do not run with this configuration in Production.";
public static void EnsureSafeForEnvironment(
string[] allowedOrigins,
bool allowAnyOrigin,
string environmentName)
{
ArgumentNullException.ThrowIfNull(allowedOrigins);
ArgumentNullException.ThrowIfNull(environmentName);
if (allowedOrigins.Length == 0
&& !allowAnyOrigin
&& string.Equals(environmentName, "Production", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(MissingOriginsMessage);
}
}
public static bool ShouldUsePermissivePolicy(string[] allowedOrigins, bool allowAnyOrigin)
{
ArgumentNullException.ThrowIfNull(allowedOrigins);
return allowAnyOrigin || allowedOrigins.Length == 0;
}
public static bool ShouldWarnAboutPermissiveDefault(string[] allowedOrigins, bool allowAnyOrigin)
{
ArgumentNullException.ThrowIfNull(allowedOrigins);
return allowedOrigins.Length == 0 && !allowAnyOrigin;
}
}