From 8754e40c9187b05199ca0a8679f968db00d46162 Mon Sep 17 00:00:00 2001 From: Andreas Mueller Date: Mon, 4 Jul 2022 19:30:40 +0200 Subject: [PATCH] BasicAuthenticationAttribute now respects the IBasicAuthenticationValidator.Realm when the own Realm property is not set. IBasicAuthenticationValidator.Realm is now a read-only property (removed public set). --- .../Attributes/BasicAuthenticationAttribute.cs | 11 +++++++++-- .../IBasicAuthenticationValidator.cs | 4 ++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/AMWD.Common.AspNetCore/Attributes/BasicAuthenticationAttribute.cs b/AMWD.Common.AspNetCore/Attributes/BasicAuthenticationAttribute.cs index d3d08ae..603d40e 100644 --- a/AMWD.Common.AspNetCore/Attributes/BasicAuthenticationAttribute.cs +++ b/AMWD.Common.AspNetCore/Attributes/BasicAuthenticationAttribute.cs @@ -73,9 +73,16 @@ namespace Microsoft.AspNetCore.Authorization private void SetAuthenticateRequest(AuthorizationFilterContext context) { + var validator = context.HttpContext.RequestServices.GetService(); + string realm = string.IsNullOrWhiteSpace(Realm) + ? string.IsNullOrWhiteSpace(validator?.Realm) + ? null + : validator.Realm + : Realm; + context.HttpContext.Response.Headers["WWW-Authenticate"] = "Basic"; - if (!string.IsNullOrWhiteSpace(Realm)) - context.HttpContext.Response.Headers["WWW-Authenticate"] += $" realm=\"{Realm.Replace("\"", "")}\""; + if (!string.IsNullOrWhiteSpace(realm)) + context.HttpContext.Response.Headers["WWW-Authenticate"] += $" realm=\"{realm.Trim().Replace("\"", "")}\""; context.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Result = new StatusCodeResult(StatusCodes.Status401Unauthorized); diff --git a/AMWD.Common.AspNetCore/BasicAuthentication/IBasicAuthenticationValidator.cs b/AMWD.Common.AspNetCore/BasicAuthentication/IBasicAuthenticationValidator.cs index d2d865b..b335966 100644 --- a/AMWD.Common.AspNetCore/BasicAuthentication/IBasicAuthenticationValidator.cs +++ b/AMWD.Common.AspNetCore/BasicAuthentication/IBasicAuthenticationValidator.cs @@ -10,9 +10,9 @@ namespace AMWD.Common.AspNetCore.BasicAuthentication public interface IBasicAuthenticationValidator { /// - /// Gets or sets the realm to use when requesting authentication. + /// Gets the realm to use when requesting authentication. /// - string Realm { get; set; } + string Realm { get; } /// /// Validates a username and password for Basic Authentication.