using ApiGateway.Security; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.BearerToken; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.DataProtection.Repositories; namespace ApiGateway; public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-api-gateway"); builder.Services.AddControllers(); builder.Services.AddProblemDetails(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddAuthentication("ClientOrService") .AddPolicyScheme("ClientOrService", null, options => options.ForwardDefaultSelector = context => context.Request.Headers.ContainsKey("X-Service-Key") ? "InternalService" : "Bearer") .AddBearerToken("Bearer", options => { options.BearerTokenExpiration = TimeSpan.FromMinutes(builder.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30)); }) .AddScheme("InternalService", null); builder.Services.AddAuthorization(options => { options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); options.AddPolicy("Patient", policy => policy.RequireRole("Patient").RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier)); options.AddPolicy("HealthcareProfessional", policy => policy.RequireRole("HealthcareProfessional") .RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier)); }); builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway"); builder.Services.AddOptions().Configure((options, configuration, logger) => { var keyDirectory = configuration["Authentication:KeyDirectory"]; if (string.IsNullOrWhiteSpace(keyDirectory)) throw new InvalidOperationException("Authentication:KeyDirectory is required."); options.XmlRepository = new FileSystemXmlRepository(new DirectoryInfo(keyDirectory), logger); }); builder.Services.AddHttpClient("PatientProfile", (services, client) => { var configuration = services.GetRequiredService(); client.BaseAddress = GetBaseUri(configuration, "PatientProfile"); client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:PatientProfile:Key"]); }) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); builder.Services.AddHttpClient("Observation", (services, client) => { var configuration = services.GetRequiredService(); client.BaseAddress = GetBaseUri(configuration, "Observation"); client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:Observation:Key"]); }) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); builder.Services.AddHttpClient("Insights", (services, client) => { var configuration = services.GetRequiredService(); client.BaseAddress = GetBaseUri(configuration, "Insights"); client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:Insights:Key"]); }) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); builder.Services.AddHttpClient("HealthOverview", (services, client) => { var configuration = services.GetRequiredService(); client.BaseAddress = GetBaseUri(configuration, "HealthOverview"); client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:HealthOverview:Key"]); }) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); var app = builder.Build(); _ = GetBaseUri(app.Configuration, "PatientProfile"); _ = GetBaseUri(app.Configuration, "Observation"); _ = GetBaseUri(app.Configuration, "Insights"); _ = GetBaseUri(app.Configuration, "HealthOverview"); foreach (var key in new[] { "Services:PatientProfile:Key", "Services:Observation:Key", "Services:Insights:Key", "Services:HealthOverview:Key", "InternalAccess:HealthOverview:Key", "InternalAccess:Observation:Key", "InternalAccess:Insights:Key" }) if (string.IsNullOrWhiteSpace(app.Configuration[key]) || app.Configuration[key]!.Length < 32) throw new InvalidOperationException($"{key} must contain at least 32 characters."); if (string.IsNullOrWhiteSpace(app.Configuration["Authentication:KeyDirectory"])) throw new InvalidOperationException("Authentication:KeyDirectory is required."); var lifetime = app.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30); if (lifetime <= 0 || lifetime > 1440) throw new InvalidOperationException("Token lifetime must be between 1 and 1440 minutes."); if (!app.Environment.IsDevelopment()) foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" }) if (GetBaseUri(app.Configuration, service).Scheme != "https") throw new InvalidOperationException("Production service endpoints must use HTTPS."); _ = app.Services.GetRequiredService(); _ = app.Services.GetRequiredService(); app.UseExceptionHandler(); app.Use(async (context, next) => { if (!app.Environment.IsDevelopment() && !context.Request.IsHttps) { context.Response.StatusCode = 400; return; } await next(context); }); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseMiddleware(); app.MapControllers(); app.Run(); } private static Uri GetBaseUri(IConfiguration configuration, string service) { var endpoint = configuration[$"Services:{service}:BaseUrl"]; if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var baseUri) || (baseUri.Scheme != "http" && baseUri.Scheme != "https") || baseUri.AbsolutePath != "/" || !string.IsNullOrEmpty(baseUri.Query) || !string.IsNullOrEmpty(baseUri.Fragment) || !string.IsNullOrEmpty(baseUri.UserInfo)) throw new InvalidOperationException($"Services:{service}:BaseUrl must be an HTTP(S) origin URL."); return baseUri; } }