Repository navigation
Web App Integration Spec
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.
-
Verify the Twingate token on every request, in one app-wide check. No route, file or
connection is reachable without it, except
GET /healthzand 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
kidto choose among the keys fromTWINGATE_JWKS_URLis fine; never take a key or key URL from the token itself, such asjku,x5uorjwk.) - 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-Userincluded). 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
Authorizationheader. -
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_AUDIENCEandTWINGATE_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).
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.
-
Deploy only to the cluster your admins gave you, and create nothing that exposes the app: no
LoadBalancerorNodePortservices, 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.
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.
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.
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 unknownkidat most about once a minute. Don't copy the keys into the code. -
Algorithm:
ES256only. Reject tokens without akid. -
Header type: the token's header has
"typ": "GAT", notJWT. Don't require or checktyp. -
Audience:
audmust equalTWINGATE_AUDIENCE. Always pass the audience to the verify call explicitly: some libraries skip the audience check entirely when it's undefined. -
Resource:
resource.addressmust exactly equal one of the addresses inTWINGATE_RESOURCE_ADDRESS(notresource.aliases, not theHostheader). The audience covers the whole Twingate network, so this check stops another app's token from working here. -
Times:
expandiatmust be present. If your library can't require them, check yourself. Allow 30 seconds of clock skew, and reject aniatmore 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
issagainst a fixed value. -
User: reject a token with no
useror nouser.email. -
Scheme: treat the
Bearerscheme name as case-insensitive.
- Token missing, malformed, or failing any check above:
401, plain-text bodyUnauthorized, headerWWW-Authenticate: Bearer. No redirect, no login page. - Valid token, but the user isn't in a group that allows the action:
403, bodyForbidden. - No signing key is available for the token because Twingate's key endpoint couldn't be reached:
503if your library makes that easy to tell apart, otherwise401. - 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.
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.
Once the token is verified, its claims include:
-
user:email,username,first_name,last_nameandgroups -
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 itsaddress
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 withtwingate:); 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
403if 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.
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:
- Generate two throwaway ES256 key pairs with different
kids. - Serve both public keys as a JWKS from a local URL, and point
TWINGATE_JWKS_URLat it. - Mint test tokens shaped like Twingate's: header
algES256,typGATand one of yourkids; claimsaud,iat,exp,user(withemailandgroups) andresource.address, and nonbf.
- Through Twingate,
GET /mereturns your email and groups. - Automated tests, using locally generated keys, expect:
-
401for: no header; the wrong scheme; a garbage token;alg: none; anHS256token; the wrongaud; the wrongresource.address; nouser.email; a token expired by more than 30 seconds; aniatmore than 30 seconds in the future; a missingexporiat; nokid; an unknownkid; a static file, an unknown path and any framework built-in page requested without a token;POST /healthzand/healthz/x; and, if the app uses them, a WebSocket or event stream opened without a token -
200for a valid token signed with either key, including with the scheme writtenbearer, and still200after the local JWKS server is stopped, for both keys, including the first request signed with the second key after the stop -
403on 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.
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 usejsonwebtoken+jwks-rsa: don't setrateLimit(it counts each key's first fetch and rejects valid users), setcacheMaxAge: 86400000, and checkexp,iatand a futureiatyourself.-
jose:createRemoteJWKSet(url, { timeoutDuration: 5000, cacheMaxAge: 86400000 }), thenjwtVerify(token, jwks, { algorithms: ["ES256"], audience, clockTolerance: 30, requiredClaims: ["exp", "iat"], maxTokenAge: "1d" }).maxTokenAgeis what rejects aniatin the future. Check the header has akidyourself: with a single key in the JWKS,joseaccepts a token without one. - WebSockets (
wsand similar): Express middleware never sees upgrade requests. Verify in the HTTP server'supgradeevent, and on failure write a401response 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: besidesPyJWKClientErrorandInvalidTokenError, the client raisesjson.JSONDecodeErrorandPyJWKSetErroron 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.jsonor static mounts. To refuse a WebSocket with a401, use thewebsocket.http.responseextension where the server supports it (uvicorn does); otherwise closing before accepting is acceptable. -
Go,
golang-jwtv5 +keyfuncv3: parse withjwt.WithValidMethods([]string{"ES256"}),jwt.WithAudience(aud),jwt.WithLeeway(30*time.Second),jwt.WithIssuedAt()andjwt.WithExpirationRequired(), and check yourself thatiatis present and the header has akid. Build the key set withkeyfunc.NewDefaultOverrideCtxandHTTPTimeout: 5*time.Second(the default of a minute also blocks startup),RefreshUnknownKID: rate.NewLimiter(rate.Every(time.Minute), 1)andRateLimitWaitMax: 5*time.Second, which is the whole deadline for an unknown-kidrefetch.
Copyright © 2025 Twingate.
Kubernetes
SSH
Web App
Operations
Development
Migration