From d1fff745048f97d8d3aec3005ff60bfa33a08437 Mon Sep 17 00:00:00 2001 From: Thomas Rittson Date: Tue, 1 Apr 2025 15:23:26 +1000 Subject: [PATCH] Make error checking more robust per Justin --- .../Authorization/OrganizationRequirementHandler.cs | 8 ++------ .../Authorization/OrganizationRequirementHelpers.cs | 7 ++++--- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/Api/AdminConsole/Authorization/OrganizationRequirementHandler.cs b/src/Api/AdminConsole/Authorization/OrganizationRequirementHandler.cs index c90af3fe5d..63c29f4073 100644 --- a/src/Api/AdminConsole/Authorization/OrganizationRequirementHandler.cs +++ b/src/Api/AdminConsole/Authorization/OrganizationRequirementHandler.cs @@ -16,15 +16,11 @@ public class OrganizationRequirementHandler( protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, IOrganizationRequirement requirement) { var organizationId = httpContextAccessor.GetOrganizationId(); - if (organizationId is null) - { - throw new Exception("No organizationId found in route. IOrganizationRequirement cannot be used on this endpoint."); - } - var organizationClaims = context.User.GetCurrentContextOrganization(organizationId.Value); + var organizationClaims = context.User.GetCurrentContextOrganization(organizationId); var providerOrganizationContext = null; // TODO - var authorized = await requirement.AuthorizeAsync(organizationId.Value, organizationClaims, providerOrganizationContext); + var authorized = await requirement.AuthorizeAsync(organizationId, organizationClaims, providerOrganizationContext); if (authorized) { diff --git a/src/Api/AdminConsole/Authorization/OrganizationRequirementHelpers.cs b/src/Api/AdminConsole/Authorization/OrganizationRequirementHelpers.cs index 4c7b9c4941..febf70f8b8 100644 --- a/src/Api/AdminConsole/Authorization/OrganizationRequirementHelpers.cs +++ b/src/Api/AdminConsole/Authorization/OrganizationRequirementHelpers.cs @@ -4,17 +4,18 @@ namespace Bit.Api.AdminConsole.Authorization; public static class OrganizationRequirementHelpers { - public static Guid? GetOrganizationId(this IHttpContextAccessor httpContextAccessor) + public static Guid GetOrganizationId(this IHttpContextAccessor httpContextAccessor) { if (httpContextAccessor.HttpContext is null) { - return null; + throw new InvalidOperationException("This method should only be called in the context of an HTTP Request."); } httpContextAccessor.HttpContext.GetRouteData().Values.TryGetValue("orgId", out var orgIdParam); if (orgIdParam == null || !Guid.TryParse(orgIdParam.ToString(), out var orgId)) { - return null; + throw new InvalidOperationException( + "A route decorated with with '[Authorize]' should include a route value named 'orgId' either through the [Controller] attribute or through a '[Http*]' attribute."); } return orgId;