How to verify domain on Microsoft Azure and CloudFlare Pages

How to verify domain on Microsoft Azure and CloudFlare Pages

Default domain verification  on Microsoft Azure requires placing a /.well-known/microsoft-identity-associaion.json file on your web server with a specific content:

The trouble is, if you deploy with CloudFlare, for example, it fails verification before even checking the content, because someone at Microsoft decided they need to verify Content-Length header first, which CloudFlare doesn't set for this request:

It is also impossible to set Content-Length header yourself for a custom URL through CloudFlare interface, and it is not possible to set it "as is" via a CloudFlare Worker/Function, but there is a trick you can do: convert response to be fixed length.

Here is a working function code that successfully passes Azure domain verification:

const overrideMicrosoft = async ({ request, next, env }) => {
    const targetPath = '/assets/microsoft-idendity-association.json';
    const url = new URL(request.url);

    if (url.pathname === targetPath) {
        const response = await next();
        const json = await response.text();
        const { writable, readable } = new FixedLengthStream(json.length);

        const enc = new TextEncoder();
        const writer = writable.getWriter();
        writer.write(enc.encode(json));

        return new Response(readable);
    } else {
        return next();
    }
}

export const onRequest = [overrideMicrosoft];

Just add it to functions/_middleware.js and you're done.

⚠️
Actually, you should use alternative domain verification procedure, but Microsoft decided to not mention it clearly for some reason. Just go to "custom domain" tab on the sidebar when inside an Active Directory and verify it via DNS record.