Search code examples
azure-api-management

restrict requests to storage account container based on blob name via request header using APIM policy


I wish to connect an an api in Azure API manangement to a storage account container. Within this storage account I wish for the api to only be able to access a specific top-level directory in the container ("myfolder"). I am attempting to implement this using an inbound processing policy, but I'm struggling with finding the relevant documentation.

I imagine this involves triggering a 403 back to the user based on either a string variable containing the relevant header containing the blob name, or based on a boolean based on whether i get a regex match with '^myfolder' on the blob name header value. Alternatively, if the previous is not possible, modifying the request such that it fails.

Other possible solutions I could see are using check-header but where the allowed values is a check against its regex value, or using validate-headers, but I haven't figured it out yet

Any pointers to a possible solution would be appreciated


Solution

  • You can do something like below using Regex

    <inbound>
        <base />
        <choose>
            <when condition="@(System.Text.RegularExpressions.Regex.IsMatch(context.Request.Headers.GetValueOrDefault("x-ms-blob-name", ""), @"^myfolder"))">
                <!-- Allow the request to proceed -->
            </when>
            <otherwise>
                <return-response>
                    <set-status code="403" reason="Forbidden" />
                    <set-header name="Content-Type" exists-action="override">
                        <value>application/json</value>
                    </set-header>
                    <set-body>
                        {
                            "error": "Access to the requested resource is forbidden. You can only access blobs within the 'myfolder' directory."
                        }
                    </set-body>
                </return-response>
            </otherwise>
        </choose>
    </inbound>
    

    OR like this

    <inbound>
    <choose>
        <when condition="@(context.Request.Headers.GetValueOrDefault("x-ms-blob-name", "").StartsWith("myfolder"))">
            <!-- Allow the request to proceed -->
        </when>
        <otherwise>
            <return-response>
                <set-status code="403" reason="Forbidden" />
                <set-header name="Content-Type" exists-action="override">
                    <value>application/json</value>
                </set-header>
                <set-body>
                    {
                        "error": "Access to the requested resource is forbidden. You can only access blobs within the 'myfolder' directory."
                    }
                </set-body>
            </return-response>
        </otherwise>
    </choose>