skip to Main Content

I want to implement a custom cors implementation, mainly because i am building a saas and need to be able to validate origins which are dynamic.

If i remove all origins in the azure functions cors tab in then enables all origins eg "*", which i don’t want. Theres no disable option.

I don’t see any options in the apim to remove it.

Any suggestions would be appriciated.

Fixed it you have to remove all the origins and add a "options" as one of the methods

2

Answers


  1. Chosen as BEST ANSWER

    simply remove all the origins, azure function apps adds one by default, then make sure you add the options method in the app function methods params.


  2. It’s not possible to "disable CORS" as CORS is enforced by a browser.

    You can potentially allow all origins on the backend. But that effectively "disables" CORS.


    So, if the situation is:

    • Browser makes a request via APIM
    • APIM should manage CORS for you
    • There is a dynamically defined list of allowed origins

    You can manage the situation purely with APIM inbound policy without making any changes to your backend.

    However, you would need to introduce a separate helper Azure Function with an HTTP trigger that will validate origin for APIM inbound policy.


    The proposed solution fully separates backend implementation (your Azure Function) and CORS configuration via APIM.

    A backend Azure Function shouldn’t be concerned about CORS as browser sends request to APIM. APIM has a static policy that loads dynamic list of allowed origins from a helper Azure Function.


    APIM inbound policy

    <inbound>
    
        <!-- Get `Origin` HTTP header from the original request and put it to `currentOrigin` variable -->
        <set-variable name="currentOrigin" value="@{
            string[] originHeaders;
            context.Request.Headers.TryGetValue("Origin", out originHeaders);
    
            return originHeaders?.FirstOrDefault();
       }" />
    
        <!--
          Send an internal POST HTTP request to a helper Azure Function that checks origin dynamically (see sample code below).
    
          Origin to check is sent via `origin` query parameter.
    
          It responds `200` if origin is allowed.
    -->
        <send-request mode="new" response-variable-name="isOriginAllowed" timeout="30" ignore-error="false">
             <set-url>@($"https://fa-we-stackowerflow-78565167-02-d.azurewebsites.net/api/is-origin-allowed?origin={(string)context.Variables["currentOrigin"]}")</set-url>
             <set-method>POST</set-method>
        </send-request>
    
        <!-- Check the status code -->
        <choose>
            <!-- If status code is `200` -->
            <when condition="@(((IResponse)context.Variables["isOriginAllowed"]).StatusCode == 200)">
                <!-- Set variable `corsAllowOrigin` to current origin -->
                <set-variable name="corsAllowOrigin" value="@((string)context.Variables["currentOrigin"])" />
            </when>
    
            <!-- Otherwise, set variable `corsAllowOrigin` to a dummy origin that will force CORS policy to fail -->
            <otherwise>
                <set-variable name="corsAllowOrigin" value="http://dummy-domain-to-fail-cors" />
            </otherwise>
        </choose>
    
        <!-- Always configure CORS policy -->
        <cors allow-credentials="true">
            <allowed-origins>
                <!-- Set only origin from `corsAllowOrigin` variable. It will be either the original one or a dummy one -->
                <origin>@((string)context.Variables["corsAllowOrigin"])</origin>
            </allowed-origins>
            <allowed-methods preflight-result-max-age="300">
                <method>*</method>
            </allowed-methods>
            <allowed-headers>
                <header>*</header>
            </allowed-headers>
            <expose-headers>
                <header>*</header>
            </expose-headers>
        </cors>
    </inbound>
    

    Sample JavaScript helper Azure Function HTTP trigger that checks if origin is in the list of allowed origins (that list can come from a DB):

    
    // HTTP trigger
    // POST /is-origin-allowed
    
    module.exports = async function (context, req) {
    
        // List of allowed origins. It can be loaded from a DB.
        const allowedOrigins = [
           "http://localhost:5173",
        ];
    
        // Get current origin from the query parameter `origin`
        const currentOrigin = req.query.origin;
    
        // Is current origin in the list of allowed origins?
        const isOriginAllowed = allowedOrigins.indexOf(currentOrigin) !== -1;
    
        // If current origin is allowed, return `200`
        const responseStatusCode = isOriginAllowed
            ? 200
            : 400;
    
        context.res = {
            status: responseStatusCode,
            body: ""
        };
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search