From 729cf124cc1b15ff1fc634ea8af4f5273824091b Mon Sep 17 00:00:00 2001 From: damienbod Date: Sun, 31 Dec 2023 07:59:15 +0100 Subject: [PATCH] open redirect protection --- .../Server/Controllers/AccountController.cs | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/content/BlazorBffAzureAD/Server/Controllers/AccountController.cs b/content/BlazorBffAzureAD/Server/Controllers/AccountController.cs index 9650645..daaccaf 100644 --- a/content/BlazorBffAzureAD/Server/Controllers/AccountController.cs +++ b/content/BlazorBffAzureAD/Server/Controllers/AccountController.cs @@ -15,9 +15,8 @@ public ActionResult Login(string? returnUrl, string? claimsChallenge) { // var claims = "{\"access_token\":{\"acrs\":{\"essential\":true,\"value\":\"c1\"}}}"; // var claims = "{\"id_token\":{\"acrs\":{\"essential\":true,\"value\":\"c1\"}}}"; - var redirectUri = !string.IsNullOrEmpty(returnUrl) ? returnUrl : "/"; - var properties = new AuthenticationProperties { RedirectUri = redirectUri }; + var properties = GetAuthProperties(returnUrl); if(claimsChallenge != null) { @@ -40,4 +39,29 @@ public IActionResult Logout() CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme); } + + /// + /// Original src: + /// https://github.com/dotnet/blazor-samples/blob/main/8.0/BlazorWebOidc/BlazorWebOidc/LoginLogoutEndpointRouteBuilderExtensions.cs + /// + private static AuthenticationProperties GetAuthProperties(string? returnUrl) + { + const string pathBase = "/"; + + // Prevent open redirects. + if (string.IsNullOrEmpty(returnUrl)) + { + returnUrl = pathBase; + } + else if (!Uri.IsWellFormedUriString(returnUrl, UriKind.Relative)) + { + returnUrl = new Uri(returnUrl, UriKind.Absolute).PathAndQuery; + } + else if (returnUrl[0] != '/') + { + returnUrl = $"{pathBase}{returnUrl}"; + } + + return new AuthenticationProperties { RedirectUri = returnUrl }; + } }