Skip to content

Web App Integration Spec

Ben Siler edited this page Oct 28, 2026 · 6 revisions

Important

Admins: this is a natural-language spec that tells AI coding agents how to validate JWTs from the Twingate Gateway in vibe-coded web apps. Copy this page and fill in the "Settings from your admins" table before you share it with vibecoders in your org. Before an app goes live, give it its own Twingate Resource with a specific address (not a shared wildcard), make sure only the Twingate Gateway can reach it inside the cluster (for example with a NetworkPolicy), and allow it outbound HTTPS to your Twingate address (for example acme.us1.twingate.com) for Twingate's public signing keys.

From your Twingate admins (IT, security or platform team), for anyone building an internal app. Give this whole page to your coding agent along with a sentence about who should be able to do what in your app.


Your app runs behind Twingate. Every request reaches it through the Twingate Gateway, from a signed-in user on an approved device, with a signed token saying who that user is. Your app's job is to verify that token on every request and use it.

The rules

  • Verify the Twingate token on every request, in one app-wide check. No route, file or connection is reachable without it, except GET /healthz and any endpoints your admins approve.
  • There is no off switch. No flag, environment variable, dev mode or fallback that skips or weakens verification. Never use the token's claims before verifying it, even when the signing keys can't be fetched. (Reading its kid to choose among the keys from TWINGATE_JWKS_URL is fine; never take a key or key URL from the token itself, such as jku, x5u or jwk.)
  • Don't build a login. No sign-in page, passwords, sessions, OAuth or SSO setup. The app needs no authentication secrets.
  • Never trust any request header for identity or decisions, whatever its name (X-Twingate-User included). Only the verified token counts. The Gateway overwrites only the headers your admins configure it to set; any other header comes from the browser.
  • Never log, store or display the token or the Authorization header.
  • Only forward the token to backend services that are part of this app (deployed and owned together with it), never to any other API, even inside your company. Those services must verify it exactly as this page describes, with this app's TWINGATE_AUDIENCE and TWINGATE_RESOURCE_ADDRESS: an API that accepts the token without those checks is access your admins can't see or control. If another team's API needs to know who the user is, ask your admins.
  • Never make the app reachable except through Twingate (see Hosting below).

Settings from your admins

Read these from configuration (environment variables), never hard-code them. If any is unset, blank, or contains < or >, refuse to start, and ask your admins for the value.

Setting Value
TWINGATE_JWKS_URL https://<your Twingate address>/api/v1/jwk/ec
TWINGATE_AUDIENCE <network>
TWINGATE_RESOURCE_ADDRESS <resource address>: this app's address in Twingate, exactly as configured. If the app is published through more than one Twingate Resource, list each address, separated by commas

<your Twingate address> is the address you see when you sign in to the Twingate Admin Console, exactly as shown, including any regional part (for example acme.us1.twingate.com). Don't shorten it: the short form can redirect, and some JWT libraries refuse to follow redirects. <network> is just the network name, the acme in that address.

Hosting and sharing

  • Deploy only to the cluster your admins gave you, and create nothing that exposes the app: no LoadBalancer or NodePort services, Ingress, port forwarding, tunnels such as ngrok, public URLs, or running it on a laptop for others. To share the app, tell your admins which team should have it.
  • Who can open the app is decided in Twingate, not in the app's code. Your admins grant groups access. The app only decides what people can do once they're in.

Verifying the token

Every request arrives with a header:

Authorization: Bearer <token>

The app needs only this header. If it needs any other header from the Gateway, ask your admins to configure it. The token is a JWT signed by Twingate. The browser never sees it: the Gateway adds it on the way to your server, so all of this happens in server code. If the app has no server code of its own (a static single-page app, or a front end from an app builder), add a small server that serves the built files and does this check.

One check, before routing

Verify the token in one app-wide layer that runs before any route, so no route can forget it. Then check groups per route or per action as the app needs. The verification must cover every path and method, including static files, framework built-ins (for example FastAPI's /docs and /openapi.json), and paths that don't exist (they get 401, not 404). It must also cover WebSocket and server-sent-event connections: verify the token on the upgrade or opening request, and close the connection (WebSocket close code 1008) once the token's exp passes. In many frameworks these don't go through the normal middleware: see the Library notes.

The default exemption is GET /healthz, matched exactly, which returns ok and nothing else. If the app needs other endpoints without the token check (a readiness check, or a route another internal service calls), ask your admins first. Add only the ones they approve, match each exactly, and never return user data or anything sensitive from them.

How to verify

Use a well-known JWT library that fetches signing keys from a JWKS URL. Don't write the cryptography yourself.

  • Keys: fetch them from TWINGATE_JWKS_URL (about a 5-second timeout) and cache them for a day; if a later fetch fails, keep using the cached keys. Most libraries drop cached keys after 5 to 10 minutes by default, so set the cache lifetime (see the Library notes). Refetch for an unknown kid at most about once a minute. Don't copy the keys into the code.
  • Algorithm: ES256 only. Reject tokens without a kid.
  • Header type: the token's header has "typ": "GAT", not JWT. Don't require or check typ.
  • Audience: aud must equal TWINGATE_AUDIENCE. Always pass the audience to the verify call explicitly: some libraries skip the audience check entirely when it's undefined.
  • Resource: resource.address must exactly equal one of the addresses in TWINGATE_RESOURCE_ADDRESS (not resource.aliases, not the Host header). The audience covers the whole Twingate network, so this check stops another app's token from working here.
  • Times: exp and iat must be present. If your library can't require them, check yourself. Allow 30 seconds of clock skew, and reject an iat more than 30 seconds in the future.
  • Do not require nbf. Twingate's tokens don't include it, so requiring it rejects every real request.
  • Issuer: don't check iss against a fixed value.
  • User: reject a token with no user or no user.email.
  • Scheme: treat the Bearer scheme name as case-insensitive.

Responses

  • Token missing, malformed, or failing any check above: 401, plain-text body Unauthorized, header WWW-Authenticate: Bearer. No redirect, no login page.
  • Valid token, but the user isn't in a group that allows the action: 403, body Forbidden.
  • No signing key is available for the token because Twingate's key endpoint couldn't be reached: 503 if your library makes that easy to tell apart, otherwise 401.
  • Never a 500, and never let a request through, whatever goes wrong. Log the reason for every refusal on the server, never the token itself.

Who's calling: /me

Expose GET /me, behind the same check as everything else. It shows the app reads the user from the verified token, whatever its interface looks like, and your admins can use it to check the integration through Twingate. It returns exactly {"email": <user.email>, "groups": <user.groups>} as application/json. Nothing else, never raw claims, never the token. Register it ahead of any catch-all or single-page-app fallback route. If the app already uses /me, use /_twingate/me and tell your admins.

What's in the token

Once the token is verified, its claims include:

  • user: email, username, first_name, last_name and groups
  • device: the device the request came from, including its approximate location (device.location, derived from IP). That's personal data: don't store or return it unless the app needs it.
  • resource: the Twingate resource being accessed, including its address

Who can do what: authorization

user.groups lists the user's group names from the company's identity provider, kept up to date as people join, move and leave. Use them to decide what each user can do in the app. The person building the app decides which groups can do what: ask them if it's unclear.

  • Ignore built-in groups (Everyone, and anything starting with twingate:); every user has them. Match group names case-insensitively.
  • Decide on the server, on every request, and deny by default. Hiding a button is fine, but any action that changes data must check the group again and respond 403 if it isn't allowed.
  • Base anything that depends on who someone is on a group, never a hard-coded list of names or emails. If the group you need doesn't exist, ask your admins to create it.
  • Tell your admins every group your app checks. The token only lists groups that have access to your app in Twingate, so a group your admins haven't added never shows up.
  • Don't block whole users or teams in code. Who can see the app at all is an access change for your admins in Twingate.
  • Read the groups from each request's token, never cached across requests, so group changes take effect within seconds.

Testing without Twingate

You can't get a real Twingate token outside Twingate, and you must not add a bypass (see The rules). Instead, in the app's automated tests:

  1. Generate two throwaway ES256 key pairs with different kids.
  2. Serve both public keys as a JWKS from a local URL, and point TWINGATE_JWKS_URL at it.
  3. Mint test tokens shaped like Twingate's: header alg ES256, typ GAT and one of your kids; claims aud, iat, exp, user (with email and groups) and resource.address, and no nbf.

Done when

  • Through Twingate, GET /me returns your email and groups.
  • Automated tests, using locally generated keys, expect:
    • 401 for: no header; the wrong scheme; a garbage token; alg: none; an HS256 token; the wrong aud; the wrong resource.address; no user.email; a token expired by more than 30 seconds; an iat more than 30 seconds in the future; a missing exp or iat; no kid; an unknown kid; a static file, an unknown path and any framework built-in page requested without a token; POST /healthz and /healthz/x; and, if the app uses them, a WebSocket or event stream opened without a token
    • 200 for a valid token signed with either key, including with the scheme written bearer, and still 200 after the local JWKS server is stopped, for both keys, including the first request signed with the second key after the stop
    • 403 on every privileged action for a valid token without the right group
  • Privileged actions work for users in the right group.
  • If the app has a user interface, the signed-in user's name or email is visible somewhere in it, taken from the verified token. Where and how is up to the app.

Library notes

Read only the part for your stack. Each closes a gap that a straightforward implementation fell into in testing.

  • Node: use jose. If you must use jsonwebtoken + jwks-rsa: don't set rateLimit (it counts each key's first fetch and rejects valid users), set cacheMaxAge: 86400000, and check exp, iat and a future iat yourself.
    • jose: createRemoteJWKSet(url, { timeoutDuration: 5000, cacheMaxAge: 86400000 }), then jwtVerify(token, jwks, { algorithms: ["ES256"], audience, clockTolerance: 30, requiredClaims: ["exp", "iat"], maxTokenAge: "1d" }). maxTokenAge is what rejects an iat in the future. Check the header has a kid yourself: with a single key in the JWKS, jose accepts a token without one.
    • WebSockets (ws and similar): Express middleware never sees upgrade requests. Verify in the HTTP server's upgrade event, and on failure write a 401 response and destroy the socket.
  • Python, PyJWT: use PyJWT 2.13 or later: earlier versions throw away the cached keys when a fetch fails. PyJWKClient(url, timeout=5, lifespan=86400). Catch every exception from the key lookup and the decode and refuse the request: besides PyJWKClientError and InvalidTokenError, the client raises json.JSONDecodeError and PyJWKSetError on a bad key response. The client is synchronous: in async code, call it in a thread.
  • Python ASGI (FastAPI, Starlette): write the check as a pure ASGI middleware that handles both scope["type"] == "http" and "websocket". @app.middleware("http") and route dependencies don't cover WebSockets, and dependencies don't cover /docs, /openapi.json or static mounts. To refuse a WebSocket with a 401, use the websocket.http.response extension where the server supports it (uvicorn does); otherwise closing before accepting is acceptable.
  • Go, golang-jwt v5 + keyfunc v3: parse with jwt.WithValidMethods([]string{"ES256"}), jwt.WithAudience(aud), jwt.WithLeeway(30*time.Second), jwt.WithIssuedAt() and jwt.WithExpirationRequired(), and check yourself that iat is present and the header has a kid. Build the key set with keyfunc.NewDefaultOverrideCtx and HTTPTimeout: 5*time.Second (the default of a minute also blocks startup), RefreshUnknownKID: rate.NewLimiter(rate.Every(time.Minute), 1) and RateLimitWaitMax: 5*time.Second, which is the whole deadline for an unknown-kid refetch.

Clone this wiki locally