diff --git a/EstateReportingAPI/Common/EstateContext.cs b/EstateReportingAPI/Common/EstateContext.cs index 22a2b76..c474575 100644 --- a/EstateReportingAPI/Common/EstateContext.cs +++ b/EstateReportingAPI/Common/EstateContext.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Authorization; +using System.Security.Claims; namespace EstateReportingAPI.Common { @@ -117,23 +118,40 @@ private async Task HandleAuthenticatedRequestAsync( EstateContext estateContext, Guid? headerEstateId) { - string? estateClaim = httpContext.User.FindFirst("estateId")?.Value; + bool isUserToken = httpContext.User.HasClaim(claim => claim.Type == ClaimTypes.NameIdentifier); - if (Guid.TryParse(estateClaim, out Guid authenticatedEstateId) == false || - authenticatedEstateId == Guid.Empty) + if (isUserToken) { - httpContext.Response.StatusCode = StatusCodes.Status403Forbidden; - return; + string? estateClaim = httpContext.User.FindFirst("estateId")?.Value; + + if (!Guid.TryParse(estateClaim, out Guid authenticatedEstateId) || + authenticatedEstateId == Guid.Empty) + { + httpContext.Response.StatusCode = StatusCodes.Status403Forbidden; + return; + } + + if (headerEstateId.HasValue && + headerEstateId.Value != authenticatedEstateId) + { + httpContext.Response.StatusCode = StatusCodes.Status403Forbidden; + return; + } + + estateContext.SetEstate(authenticatedEstateId); } - - if (headerEstateId.HasValue && headerEstateId.Value != authenticatedEstateId) + else { - httpContext.Response.StatusCode = StatusCodes.Status403Forbidden; - return; + // Client-credentials token: tenant comes from the trusted ACL header. + if (!headerEstateId.HasValue) + { + httpContext.Response.StatusCode = StatusCodes.Status403Forbidden; + return; + } + + estateContext.SetEstate(headerEstateId.Value); } - estateContext.SetEstate(authenticatedEstateId); - await _next(httpContext); } }