Skip to content

Commit

Permalink
actually make the thing
Browse files Browse the repository at this point in the history
  • Loading branch information
Dougley committed Mar 31, 2024
1 parent aa0a05e commit 53cc96c
Show file tree
Hide file tree
Showing 3 changed files with 116 additions and 24 deletions.
32 changes: 32 additions & 0 deletions .github/workflows/charts.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: Release Charts

on:
push:
branches:
- main

jobs:
release:
# depending on default permission settings for your org (contents being read-only or read-write for workloads), you will have to add permissions
# see: https://docs.github.com/en/actions/security-guides/automatic-token-authentication#modifying-the-permissions-for-the-github_token
permissions:
contents: write
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0

- name: Configure Git
run: |
git config user.name "$GITHUB_ACTOR"
git config user.email "[email protected]"
- name: Install Helm
uses: azure/setup-helm@v3

- name: Run chart-releaser
uses: helm/[email protected]
env:
CR_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
39 changes: 36 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,44 @@ This is a simple way to validate JSON Web Keys (JWK) in Nginx using [Nginx Exter

Keep in mind that this service is purely meant to **validate** already signed tokens. It does not sign tokens or provide any other functionality. Your IdP should do more granular access control, and this service should only be used to validate the token signature.

Ideally, your IdP has [OpenID Connect Discovery 1.0](https://openid.net/specs/openid-connect-discovery-1_0.html) compliant discovery endpoint, and it at least exposes the `issuer` and `jwks_uri` fields. If your IdP does not provide a OIDC Discovery endpoint, you can still use this service by providing the JWK URI and issuer manually.
Ideally, your IdP has a [OpenID Connect Discovery 1.0](https://openid.net/specs/openid-connect-discovery-1_0.html) compliant discovery endpoint, and it at least exposes the `issuer` and `jwks_uri` fields. If your IdP does not provide a OIDC Discovery endpoint, you can still use this service by providing the JWK URI and issuer manually.

## Usage
## Setup

> **Note**
> [!NOTE]
> Using Kubernetes? Use [Helm](https://helm.sh/) to deploy this service. Check out the [Helm chart]().
1. Clone this repository
2. Find your IdP's OIDC Discovery endpoint or JWK URI. For example, Google's OIDC Discovery endpoint is `https://accounts.google.com/.well-known/openid-configuration`, it's JWK URI is `https://www.googleapis.com/oauth2/v3/certs`.
- If your IdP does not provide a OIDC Discovery endpoint, you should set a default issuer and JWK URI manually. The issuer is optional, but recommended.
3. Run the service with the following environment variables:
- `OIDC_DISCOVERY_URI`: The URI to the OIDC Discovery endpoint. **Recommended way to configure**. For example, `https://accounts.google.com/.well-known/openid-configuration`.
- `JWK_URI`: The URI to the JWK set. For example, `https://www.googleapis.com/oauth2/v3/certs`. Only required if `OIDC_DISCOVERY_URI` is not set.
- `JWT_ISSUER`: The default issuer of the JWT. Optional. Gets automatically populated if `OIDC_DISCOVERY_URI` is set.
- `JWT_AUDIENCE`: The audience tag that the JWT should have. Optional.
- `JWT_HEADER`: The header to look for the JWT in. Default is `Authorization`.
- `PORT`: The port to listen on. Default is `8080`.

`JWT_AUDIENCE` and `JWT_ISSUER` can be overridden by using the `aud` and `iss` query parameters in the request, this is useful if you have multiple audiences or issuers.

# Usage

Since this service is meant to be used with Nginx External Authentication, you should configure your Nginx to use this service as an external auth provider. Here is an example configuration:

```nginx
location / {
auth_request /auth;
error_page 401 = /auth_error;
# Your application
proxy_pass http://your_application;
}
location = /auth {
internal;
proxy_pass http://localhost:8080;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
```
69 changes: 48 additions & 21 deletions src/index.mts
Original file line number Diff line number Diff line change
@@ -1,14 +1,26 @@
import Fastify from "fastify";
import { createRemoteJWKSet } from "jose";
import { JWTPayload, jwtVerify } from "jose";
import { JWTPayload, jwtVerify, createRemoteJWKSet } from "jose";

if (!process.env.JWKS_URI && !process.env.OIDC_DISCOVERY_URI) {
console.error("JWKS_URI is required if OIDC_DISCOVERY_URI is not provided");
process.exit(1);
}

if (process.env.OIDC_DISCOVERY_URI) {
const discovery = await fetch(process.env.OIDC_DISCOVERY_URI);
const discoveryJson = (await discovery.json()) as {
jwks_uri: string;
issuer: string;
};
process.env.JWKS_URI = discoveryJson.jwks_uri;
process.env.JWT_ISSUER = discoveryJson.issuer;
}

const fastify = Fastify({
logger: true,
});

const JWKS = createRemoteJWKSet(
new URL("https://dougley.cloudflareaccess.com/cdn-cgi/access/certs"),
);
const JWKS = createRemoteJWKSet(new URL(process.env.JWKS_URI!));

fastify.get<{
Querystring: {
Expand All @@ -19,21 +31,36 @@ fastify.get<{
authorization: string;
};
}>("/", async (request, reply) => {
const { payload, protectedHeader } = await jwtVerify(
request.headers.authorization,
JWKS,
{
issuer: request.query.iss,
audience: request.query.aud,
},
);
return { payload, protectedHeader };
});

fastify.listen({ port: 8080, host: "0.0.0.0" }, function (err, address) {
if (err) {
fastify.log.error(err);
process.exit(1);
const header = process.env.JWT_HEADER ?? "authorization";
if (!request.headers[header]) {
reply.status(401).send({ error: "Unauthorized" });
return;
}
request.headers.authorization = Array.isArray(request.headers[header])
? request.headers[header]![0]
: (request.headers[header] as string);
const jwt = request.headers.authorization.startsWith("Bearer ")
? request.headers.authorization.slice(7)
: request.headers.authorization;
try {
const { payload, protectedHeader } = await jwtVerify(jwt, JWKS, {
issuer: request.query.iss ?? process.env.JWT_ISSUER ?? undefined,
audience: request.query.aud ?? process.env.JWT_AUDIENCE ?? undefined,
});
return { payload, protectedHeader };
} catch (e) {
console.log("Verification failed", e);
reply.status(401).send({ error: "Unauthorized" });
}
fastify.log.info(`server listening on ${address}`);
});

fastify.listen(
{ port: +(process.env.PORT ?? 8080), host: "0.0.0.0" },
function (err, address) {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info(`server listening on ${address}`);
},
);

0 comments on commit 53cc96c

Please sign in to comment.