Worker to append new Headers for Service Auth Tunnel Access

Hi, scratching my head a little bit as I’ve tried a lot and nothing seems to work.

Scenario
I’d like to use Service Auth Token to access a service behind CF tunnel with Application Access Policy setup for the clients that can’t both:

  • authenticate via web browser (OIDC)
  • add custom headers on the client side

Tunnel Setup
I have Cloudflare Tunnel configured with Service Auth Application Access Policy. If I test if it operates correctly.
Using:
curl -vv -H "CF-Access-Client-Secret: REDACTED" -H "CF-Access-Client-Id: REDACTED.access" https://subd.tld
I do get the expected response (i.e. page from the tunneled service with Access Policy correctly applied). In other words the added headers do work as intended.

Unfortunately this is not something I can replicate on the client, hence:

Worker / Workers Routes Setup
Now I’d like to create a Worker, that adds these two Headers into every request automatically. After a lot of testing and trial/error, I’ve come up with this worker code:

export default {
  async fetch(request, env) {
    try {
      
      const newHeaders = new Headers(request);
      newHeaders.set('CF-Access-Client-Id', 'REDACTED.access');
      newHeaders.set('CF-Access-Client-Secret', 'REDACTED');
      
      const myInit = {
        headers: newHeaders,
      };

      
      const newRequest = new Request(request, myInit);
      return fetch(newRequest);
    } catch(e) {
      return new Response(err.stack, { status: 500 })
    }
  }
}

The worker route is setup correctly, Route is *subd.tld/* and Service is my Worker. The subd.tld is DNS Cached.

But no matter what I try, the headers don’t get added to the request. Is the code wrong, or is there some CF limitation like Header names I can’t use, or is that Workers don’t work before Tunnels Application Access Policy gets evaluated?

Correct.

Access happens before Workers, so you cannot have this particular Worker on the same URL as the Access policy.

2 Likes