@autotelic/oauth-gateway-worker

A template for kick starting a Cloudflare Workers project

Usage no npm install needed!

<script type="module">
  import autotelicOauthGatewayWorker from 'https://cdn.skypack.dev/@autotelic/oauth-gateway-worker';
</script>

README

API Oauth

A cloudflare worker to provide authentication for an API (currently setup for Github oauth).

TODO: make oauth and route configurable so this is a generic worker template for the generate command.

Setup

npm i @autotelic/oauth-gateway-worker

 Cloudflare environments and deployment

wrangler.toml.example is setup to show that there is a "dev" version of the worker deployed to the worker subdomain, and a "production" version.

Both environments require these secrets:

  • GITHUB_APP_CLIENT_ID - the client id of a github app
  • GITHUB_APP_CLIENT_SECRET - the client secret of the same github app
  • B64URL_TOKEN_ENCRYPTION_KEY - an AES-GCM-256 key base64url encoded for symmetrically encrypting/decrypting the token we return
  • kv-namespaces[].id - ID of the production AUTH_STORE namespace
  • kv-namespaces[].preview_id - ID of the dev AUTH_STORE namespace

In addition OAUTH_REDIRECT_URI is defined in wrangler.toml

Until we have a GH action, deployment is using the wrangler cli:

$ wrangler publish

or

$ wrangler publish --env production

See the wrangler docs for more.

Running locally in development

$ wrangler dev

will setup a local server to run the worker from your codebase, by default on http://localhost:8787

If you would like to forward the requests to a locally running instance of the API, first run an ngrok tunnel pointing to your local instance of the API:

$ ngrok http 3000

(this assumes your API instance is running locally on port 3000)

Then grab the https ngrok url you are given, and update the UPSTREAM_HOST in the wrangler.toml vars.

Restart wrangler dev to pick up the change. Your local worker should now proxy via the ngrok tunnel to the local API.

(It seems that cloudflare throws an error when you proxy to localhost, unfortunately)

On Heroku

If you are running the downstream API on Heroku, you will need to:

Usage

  • go to /login to be redirected to the authorization page
  • this will redirect to /callback and display a generated and encrypted token
  • use the token in an Authorization: Bearer <token> header for http requests to any other path of the API