Validate the Access token with FastAPI
Last updated Apr 17, 2026 This tutorial covers how to validate that the Access JWT is on requests made to FastAPI apps.
Time to complete: 15 minutes
Prerequisites
- A self-hosted Access application for your FastAPI app
- The AUD tag for your Access application
1. Create a validation function
- In your FastAPI project, create a new file called
cloudflare.pythat contains the following code:
from fastapi import Request, HTTPException
# The Application Audience (AUD) tag for your application
POLICY_AUD = "XXXXX"
# Your CF Access team domain
TEAM_DOMAIN = "https://<your-team-name>.cloudflareaccess.com"
CERTS_URL = "{}/cdn-cgi/access/certs".format(TEAM_DOMAIN)
async def validate_cloudflare(request: Request):
"""
Validate that the request is authenticated by Cloudflare Access.
"""
if verify_token(request) != True:
raise HTTPException(status_code=400, detail="Not authenticated properly!")
def _get_public_keys():
"""
Returns:
List of RSA public keys usable by PyJWT.
"""
r = requests.get(CERTS_URL)
public_keys = []
jwk_set = r.json()
for key_dict in jwk_set["keys"]:
public_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(key_dict))
public_keys.append(public_key)
return public_keys
def verify_token(request):
"""
Verify the token in the request.
"""
token = ""
if "CF_Authorization" in request.cookies:
token = request.cookies["CF_Authorization"]
else:
raise HTTPException(status_code=400, detail="missing required cf authorization token")
keys = _get_public_keys()
# Loop through the keys since we can't pass the key set to the decoder
valid_token = False
for key in keys:
try:
# decode returns the claims that has the email when needed
jwt.decode(token, key=key, audience=POLICY_AUD, algorithms=["RS256"])
valid_token = True
break
except:
raise HTTPException(status_code=400, detail="Error decoding token")
if not valid_token:
raise HTTPException(status_code=400, detail="Invalid token")
return True
2. Use the validation function in your app
You can now add the validation function as a dependency in your FastAPI app. One way to do this is by creating an APIRouter instance ↗︎. The following example executes the validation function on each request made to paths that start with /admin:
from fastapi import APIRouter, Depends, HTTPException
from cloudflare import validate_cloudflare
router = APIRouter(
prefix="/admin",
tags=["admin"],
dependencies=[Depends(validate_cloudflare)]
responses={404: {"description": "Not found"}},
)
@router.get("/")
async def root():
return {"message": "Hello World"}
Was this helpful?
YesNo
On this page
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/cloudflare-one/tutorials/fastapi/#page","headline":"Validate the Access token with FastAPI","description":"This tutorial covers how to validate that the Access JWT is on requests made to FastAPI apps. The code is written in Python.","url":"https://developers.cloudflare.com/cloudflare-one/tutorials/fastapi/","inLanguage":"en","image":"https://developers.cloudflare.com/cloudflare-one/tutorials/fastapi/og.png?v=6aaaa7c44c65c195","dateModified":"2026-04-17","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"},"keywords":["Python"]}
description: Learn how to add Zero Trust rules to a self-hosted instance of GitLab. This tutorial walks you through deploying GitLab in DigitalOcean. title: Zero Trust GitLab SSH & HTTP image: https://developers.cloudflare.com/cloudflare-one/tutorials/gitlab/og.png?v=a44249b886b3ab0f
Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/cloudflare-one/llms.txt
Use this file to discover all available pages before exploring further.
Docs