From ff81325020d4786d1ee1b62134af431a3f392693 Mon Sep 17 00:00:00 2001 From: Khwezi Mngoma Date: Sun, 17 May 2026 11:34:40 +0200 Subject: [PATCH] Refactored forced https redirection --- ShopAdmin/Program.cs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/ShopAdmin/Program.cs b/ShopAdmin/Program.cs index fcd9856..fa01f7d 100644 --- a/ShopAdmin/Program.cs +++ b/ShopAdmin/Program.cs @@ -65,15 +65,18 @@ builder.Services.AddAuthentication(options => RoleClaimType = "groups" }; - builder.Services.AddOptions(OpenIdConnectDefaults.AuthenticationScheme).Configure(options => + options.Events = new OpenIdConnectEvents { - options.Events.OnRedirectToIdentityProvider = context => + OnRedirectToIdentityProvider = context => { - context.ProtocolMessage.RedirectUri = context.ProtocolMessage.RedirectUri.Replace("http://", "https://"); - + var fallbackUri = context.ProtocolMessage.RedirectUri; + + if (fallbackUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) + context.ProtocolMessage.RedirectUri = fallbackUri.Replace("http://", "https://", StringComparison.OrdinalIgnoreCase); + return Task.CompletedTask; - }; - }); + } + }; }); builder.Services.Configure(options => @@ -90,6 +93,8 @@ var scheduler = await schedulerFactory.GetScheduler(ShopSchedulerName); if (!scheduler!.IsStarted) await scheduler.Start(); +app.UseForwardedHeaders(); + if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); @@ -105,7 +110,6 @@ app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: app.UseHttpsRedirection(); app.UseAntiforgery(); -app.UseForwardedHeaders(); app.UseAuthentication(); app.UseAuthorization(); @@ -114,6 +118,7 @@ app.MapStaticAssets(); app.MapGet("/auth/login", (string redirectUri = "/") => Results.Challenge(new AuthenticationProperties { RedirectUri = redirectUri }, [OpenIdConnectDefaults.AuthenticationScheme])); + app.MapGet("/auth/logout", async (HttpContext context) => { await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); -- 2.47.3