Logging in to my anonymous chat admin page on a Raspberry Pi from outside the LAN with OIDC, without opening ports
Here is what this post covers:
- Introduction
- The overall setup
- Cloudflare Tunnel with no open ports
- Mapping the OIDC roles
- The login flow
- The Cloudflare Access JWT that reaches Rails
- Validating the JWT in Rails
- Why Rails checks as well
- Wrapping up
- References
Introduction
I built and released an anonymous chat called anontopic as a personal project. It is out there, but nobody comes. Not a soul. With no visitors there are no trolls or reports yet either, but to be ready for when they arrive, I built a separate admin page for managing topics, reviewing reports and banning users. The admin page is a Rails app that does nothing but call the main service’s admin API.
It runs as a container on a Raspberry Pi at home. That part is a trivial chore: after docker compose up, you can open it from anywhere on the same LAN.
The trouble starts when I want to open it while I am out. I do not want to open a port on the router and put the admin page straight onto the internet, and building a login system from scratch for an app whose only admin is me is a pain I can do without.
So I connected it to the outside with Cloudflare Tunnel, which needs no open ports, and put Cloudflare Access in front so that you log in with a Google account. The login is Google’s OIDC (OpenID Connect), and Rails validates the JWT it receives and returns 403 if it does not match.
This post follows that setup step by step. In earlier posts I used diagrams to explain the authorization code flow, PKCE and OpenID Connect. This time I apply the terms from those posts, such as OP, RP and ID token, to a real setup.
The overall setup
On its way from the browser to the admin page, a request passes through these places.
The numbers in the rounded labels are the port numbers of each connection. A request from outside first stops at Cloudflare Access, on Cloudflare’s edge. It sends anyone who has not logged in to the Google login, and lets through only people whose email address is on the allow list. A request that gets through travels down the Tunnel to cloudflared on the Raspberry Pi, and cloudflared hands it to Rails on the same Docker network.
The thing to notice in the diagram is that there are two signed tokens. Cloudflare Access sits in the middle of both: it validates the green ID token and issues the orange JWT. The green one comes from Google, and the orange one is validated by Rails. The ID token Google issues never reaches Rails. It can look as if Rails validates Google’s token directly, but what it actually validates is a JWT signed by Cloudflare. I come back to this in “Mapping the OIDC roles”.
The main admin API at the bottom right is outside this story. Rails calls it with a static token shared with the main service, sent in Authorization: Bearer. A person logging in (who opened the admin page) and trust between servers (whether a request came from the admin page) are protected by separate mechanisms.
Cloudflare Tunnel with no open ports
No router port has to be opened because the connection goes the other way. cloudflared opens a connection from inside the Raspberry Pi out to Cloudflare, and requests from outside flow back along that connection. Not a single connection comes into the house.
cloudflared connects to port 7844 on Cloudflare. The browser away from home connects to port 443 on Cloudflare and never reaches the Pi directly.
For the technical details of what cloudflared does inside (multiplexing over QUIC or HTTP/2, redundant connections and so on), see the Cloudflare Tunnel documentation and the cloudflared source.
In compose.yaml, cloudflared sits next to the admin app, admin.
services:
admin:
build: .
env_file: .env
# Only expose it on the Pi's 127.0.0.1, so it cannot be reached from outside
ports:
- "127.0.0.1:3000:3000"
# (read_only and healthcheck omitted)
cloudflared:
image: cloudflare/cloudflared:2026.10.7
profiles: ["tunnel"]
restart: unless-stopped
command: ["tunnel", "--no-autoupdate", "run"]
environment:
TUNNEL_TOKEN: ${TUNNEL_TOKEN}
depends_on:
admin:
condition: service_healthy
The cloudflared image comes from cloudflare/cloudflared on Docker Hub. It is the Tunnel client that Cloudflare publishes, and since there are ARM images too, it runs on a Raspberry Pi as is. I pin the version instead of using latest.
TUNNEL_TOKEN is the string the Cloudflare dashboard shows when you create a tunnel. The cloudflared that holds it connects to Cloudflare as that tunnel.
Which hostname goes where is set in the tunnel’s settings on the dashboard. I send admin.anonymtopic.com to http://admin:3000. admin is the compose service name, so it only resolves inside the same Docker network.
profiles: ["tunnel"] means cloudflared only starts when .env sets COMPOSE_PROFILES=tunnel. To try things on the LAN, I can run just admin without the tunnel.
Between the browser and Cloudflare the connection is HTTPS, but from cloudflared to Rails it is plain HTTP. HTTPS ends at Cloudflare, so RAILS_ASSUME_SSL=true tells Rails to treat the outside as HTTPS. Without it, the https:// Origin the browser sends does not match what Rails expects, and every form submission is refused as CSRF.
Mapping the OIDC roles
Now for authentication. In the OpenID Connect post, I called the OIDC parties the OP (OpenID Provider) and the RP (Relying Party). The OP proves who the user is, and the RP relies on that proof to log the user in. Applied to this setup, they look like this.
| OIDC role | Who it is here | What it does |
|---|---|---|
| End user | Me (the admin) | Logs in with Google |
| OP | Checks who I am with a password and 2-step verification, and issues the ID token | |
| RP | Cloudflare Access | Validates the ID token and checks the email address against the allow list |
| (outside OIDC) | Rails | Validates the JWT that Cloudflare Access issues |
The third and fourth rows are what matter. The RP is not Rails, it is Cloudflare Access. The client ID and secret of the OAuth client I created in the Google Cloud console went into the Cloudflare dashboard. Neither is stored on the Raspberry Pi.
Rails takes no part in the OIDC exchange. It handles no redirects and no authorization codes. It only checks the JWT that Cloudflare Access attaches to the request headers. A proxy like this, which stands in front of an app, handles login on its behalf and passes the result in a header, is called an identity-aware proxy (the overview of Google Cloud’s service of the same name, Identity-Aware Proxy, explains the idea well).
The login flow
Here is what happens when I open the admin page for the first time, without a Cloudflare Access cookie. Green is the OIDC exchange with Google, and orange is the JWT handed to Rails.
Steps 1 to 8 are almost the same as the flow in the authorization code flow post. The differences are that the scope in the authorization request in step 3 includes openid, and that in step 8 an ID token comes back together with the access token. This is exactly the shape from the OIDC post.
The redirect URI registered with Google is https://<team-name>.cloudflareaccess.com/cdn-cgi/access/callback. The redirect in step 5 carries the authorization code back to Cloudflare Access, so you register its URL, not the Rails URL. This is another sign that the RP is not Rails.
2-step verification and passkeys are required by Google in step 4. The admin page does nothing for them. If the Google account requires 2-step verification, that becomes the strength of the admin page’s login as it is.
In step 9, Cloudflare Access validates the ID token and compares its email with the policy attached to the application (the list of allowed email addresses). If it fails here, Cloudflare shows its own error page and the request never reaches Rails.
If it passes, Cloudflare Access creates a JWT signed with its own key and hands it to the browser as a cookie in step 10. From then on, every time it forwards a request in step 12, it attaches the same JWT in the Cf-Access-Jwt-Assertion header. From the second visit on, the cookie is already there, so the flow jumps from step 1 straight to step 12. The cookie lasts as long as the session duration set on the application.
The Cloudflare Access JWT that reaches Rails
The JWT that reaches Rails is not Google’s ID token, but it looks very similar. Like the token in Inside the ID token, it is a signed JWT split into header.payload.signature, and its payload carries claims like these.
| Claim | Cloudflare Access JWT | Google ID token |
|---|---|---|
iss | https://<team-name>.cloudflareaccess.com | https://accounts.google.com |
aud | The AUD tag of the Cloudflare Access application | The RP's client ID |
email | Email address of the person who logged in | Same |
exp | Expiry time | Same |
| Signing key | Cloudflare Access's private key | Google's private key |
The differences are in iss and aud. iss is the issuer, which is the Cloudflare team domain. aud says whom the token is meant for. Where an ID token would carry the RP’s client ID, this JWT carries the AUD tag assigned to each Cloudflare Access application. Even if I create another application in the same account, JWTs for that one have a different aud and do not pass on this admin page.
The public keys for checking the signature are published as a JWKS (JSON Web Key Set) at https://<team-name>.cloudflareaccess.com/cdn-cgi/access/certs. It works the same way as Google publishing the public keys for its ID tokens at its jwks_uri. Cloudflare Access rotates these keys every few weeks, so instead of saving them to a file, the app fetches them when it needs them.
Validating the JWT in Rails
In Rails, a before_action validates every request.
class ApplicationController < ActionController::Base
before_action :require_cloudflare_access
private
def require_cloudflare_access
verifier = CloudflareAccess::TokenVerifier.default
return if verifier.nil? # Nothing is checked when Cloudflare Access is not configured
email = verifier.verify(request.headers["Cf-Access-Jwt-Assertion"])
logger.info("Cloudflare Access: #{email}")
rescue CloudflareAccess::TokenVerifier::Invalid => e
logger.warn("Cloudflare Access refused the request: #{e.message}")
render plain: t("errors.cloudflare_access"), status: :forbidden
end
end
The checks live in CloudflareAccess::TokenVerifier, and the JWT handling is left to ruby-jwt.
module CloudflareAccess
class TokenVerifier
class Invalid < StandardError; end
KEYS_TTL = 1.hour
def initialize(team_domain:, audience:)
@issuer = "https://#{team_domain}"
@audience = audience
@mutex = Mutex.new
@connection = Faraday.new(url: @issuer) { |f| f.response :json }
end
# Returns the email address if the token is good, raises Invalid if not
def verify(token)
raise Invalid, "no Cf-Access-Jwt-Assertion header" if token.blank?
payload, = JWT.decode(token, nil, true,
algorithms: [ "RS256" ],
jwks: method(:keys),
iss: @issuer, verify_iss: true,
aud: @audience, verify_aud: true)
payload.fetch("email")
rescue JWT::DecodeError, KeyError => e
raise Invalid, e.message
end
private
# Called when JWT.decode needs the public keys
def keys(options)
@mutex.synchronize do
if @keys.nil? || options[:kid_not_found] || Time.current >= @keys_expire_at
@keys = { keys: @connection.get("/cdn-cgi/access/certs").body.fetch("keys") }
@keys_expire_at = KEYS_TTL.from_now
end
@keys
end
end
end
end
(The real code also sets timeouts and handles a failed key fetch.)
Here is what it checks, side by side with What the RP validates from the OIDC post.
| What | How Rails checks it |
|---|---|
| Header | Without Cf-Access-Jwt-Assertion, the request did not come through Cloudflare Access, so 403 |
| Signature | Pick the key matching the header's kid from the JWKS and check with RS256 |
iss | Was it issued by my team domain? |
aud | Does it carry this admin page's AUD tag? |
exp | Has it expired? (JWT.decode checks this by default) |
The nonce that an OIDC RP checks is missing here. The nonce was for matching the value the RP made when sending the authorization request against the value in the ID token that comes back, to stop a token being swapped in. Rails never sends an authorization request, so it has nothing to match against. Checking the nonce is the job of the RP, which is Cloudflare Access.
The public keys are reused for an hour, and fetched again on the spot when a token arrives with an unknown kid. When no key matches the kid, ruby-jwt calls keys once more with kid_not_found: true. Even right after Cloudflare Access rotates its keys, the app can validate with the new key without waiting an hour.
If any one check fails, Rails returns 403 with the message “the admin page cannot be opened because the request did not come through Cloudflare Access” and logs the reason. If everything passes, it logs the email and returns the page. That log is how I can tell who did what.
The /up endpoint used for the container’s health check is served by Rails’s Rails::HealthController, so it does not go through the before_action in ApplicationController. A health check without a JWT does not fail with 403.
Why Rails checks as well
Cloudflare Access already stops requests at the entrance, so why check again in Rails? Because the entrance can only stop requests that come through Cloudflare.
The admin page’s port is only exposed on the Raspberry Pi’s 127.0.0.1. Normally it cannot be reached from outside, but after a configuration mistake, or when another process on the Pi sends a request straight to port 3000, the request never passes the entrance. If Rails checks the signature, it can refuse those requests too. Without Cloudflare Access’s private key, nobody can make a JWT with a valid signature.
In fact, running curl http://127.0.0.1:3000/ on the Raspberry Pi returns 403. That confirms Rails is refusing requests that did not come through Cloudflare Access.
The trade-off is that when Cloudflare has an outage, I cannot open the page from outside, and I cannot open it over an SSH port forward either. In that case I empty CF_ACCESS_TEAM_DOMAIN and CF_ACCESS_AUD in .env and restart. If either is empty, TokenVerifier.default returns nil and Rails lets requests through without checking.
Wrapping up
- The admin page on the Raspberry Pi is connected to the outside with Cloudflare Tunnel, with no open ports, and Cloudflare Access in front makes you log in with a Google account
- In OIDC terms the OP is Google and the RP is Cloudflare Access, and Rails takes no part in that exchange
- What Rails validates is not Google’s ID token but the JWT that Cloudflare Access signs. It checks the signature,
iss,audandexp, and returns 403 if any of them fails - Checking in Rails as well means requests that bypass Cloudflare Access are refused too
When I worked through OAuth and OIDC in the earlier posts, I used a made-up service. Building it for real, I found that deciding first who the RP is makes it much clearer which value goes where. The client ID and secret go into Cloudflare, the redirect URI is on a Cloudflare domain, and Rails does not need to look at a nonce, all because the RP is Cloudflare Access.
That said, although this is OIDC, it is a bit different in flavor from the earlier posts. Between Cloudflare Access and Google it is the same OAuth 2.0 authorization code flow as before, and an access token does come back. But nothing uses that access token to call an API. The only part in use is checking who someone is with the ID token (authentication). That is the difference from the earlier posts, where authorization, “may the service read my photos?”, was the main topic.
That said, still nobody comes to the anonymous chat itself, so this admin page has nothing to do yet.
References
- Cloudflare Tunnel (Cloudflare Docs)
- cloudflared (GitHub)
- Validate JWTs (Cloudflare Docs)
- OpenID Connect Core 1.0
- ruby-jwt
- cloudflare/cloudflared (Docker Hub)
- Identity-Aware Proxy overview (Google Cloud)
- Understanding the OAuth authorization code flow with diagrams
- Understanding OAuth PKCE with diagrams
- Understanding OpenID Connect with diagrams