Search code examples
fetchoffice-scripts

CORS issue when calling API via Office Scripts Fetch


I am trying to make an API call via Office Scripts (fetch) to a publicly available Azure Function-based API I created. By policy we need to have CORS on for our Azure Functions. I've tried every domain I could think of, but I can't get the call to work unless I allow all origins. I've tried:

The first is the Excel Online domain I'm trying to execute from, and the rest came up during the script run in Chrome's Network tab. The error message in office Scripts doesn't tell me the domain the request is coming from like it does from Chrome's console. What host do I need to allow for Office Scripts to be able to make calls to my API?


Solution

  • The expected CORS settings for this is: https://*.officescripts.microsoftusercontent.com.

    However, Azure Functions CORS doesn't support wildcard subdomains at the moment. If you try to set an origin with wildcard subdomains, you will get the following error:

    Azure Functions CORS doesn't support wildcard subdomains

    One possible workaround is to explicitly maintain an "allow-list" in your Azure Functions code. Here is a proof-of-concept implementation (assuming you use node.js for your Azure Functions):

    module.exports = async function (context, req) {
    
        // List your allowed hosts here. Escape special characters for the regular expressions.
        const allowedHosts = [
            /https\:\/\/www\.myserver\.com/,
            /https\:\/\/[^\.]+\.officescripts\.microsoftusercontent\.com/
        ];
    
        if (!allowedHosts.some(host => host.test(req.headers.origin))) {
            context.res = {
                status: 403, /* Forbidden */
                body: "Not allowed!"
            };
            return;
        }
    
        // Handle the normal request and generate the expected response.
    
        context.res = {
            status: 200,
            body: "Allowed!"
        };
    }
    

    Please note:

    • Regular expressions are needed to match the dynamic subdomains.
    • In order to do the origin check within the code, you'll need to set * as the Allowed Origins on your Functions CORS settings page.

    Or if you want to build you service with ASP.NET Core, you can do something like this: https://stackoverflow.com/a/49943569/6656547.