- Shopify
- Engineering
Verifying Shopify Session Tokens in FastAPI
Learn how to validate JWT session tokens from Shopify App Bridge inside a Python FastAPI backend.
How to Verify Shopify Session Tokens in FastAPI with PyJWT
When you build an embedded app for Shopify merchants, the usual cookie-based login stops working. The admin loads your app inside an iframe, and third-party cookies are blocked or unreliable there. Shopify solves this with Shopify session tokens: short-lived JWTs that App Bridge creates for you. If your backend runs on Python FastAPI, you need a clean way to check those tokens and pull out the shop before any business logic runs.
Writing the verification yourself, instead of hiding it behind third-party middleware, has a real benefit. You can see every claim, check the issuer, and match the audience against your own app credentials. This guide builds the whole thing: a reusable FastAPI dependency, protected routes, token exchange, and tests.
Understanding Shopify Session Tokens and App Bridge
Shopify App Bridge gives your frontend a fresh session token whenever it needs one, and each token lives for about 60 seconds. You send it to your backend in the Authorization header as a Bearer token. Shopify signs it with your app client secret using HMAC-SHA256 (HS256).
Here are the claims you care about:
Claim What it holds
- **`iss`**: The shop admin URL, like `https://my-store.myshopify.com/admin`
- **`dest`**: The shop domain URL, like `https://my-store.myshopify.com`
- **`aud`**: Your app client ID (also called the API key)
- **`sub`**: The Shopify user id of the merchant staff member
- **`exp`, `nbf`**: Expiry time and not-before time
- **`jti`, `sid`**: A unique token id and a session id
A unique token id and a session id
One thing worth clearing up: session tokens and webhooks are verified differently. Webhooks use an HMAC signature header that you compare against the raw request body, which I covered in Shopify Webhook Verification: Raw Body HMAC in Node.js. Session tokens are real JWTs, so you must decode them, check the signature, and validate the claims.
Project Setup
pip install fastapi uvicorn pyjwt httpx pytestKeep your credentials in environment variables, never in the code.
import os
class Settings:
shopify_api_key: str = os.environ["SHOPIFY_API_KEY"] # client ID
shopify_api_secret: str = os.environ["SHOPIFY_API_SECRET"] # client secret
settings = Settings()Implementing the FastAPI Dependency for JWT Validation
For clean FastAPI JWT validation, I write one reusable dependency with PyJWT. It reads the Bearer token, decodes it with your client secret, and enforces the rules that matter: the algorithm, the audience, the required claims, and the issuer.
import re
from dataclasses import dataclass
from urllib.parse import urlparse
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from app.config import settings
bearer_scheme = HTTPBearer(auto_error=False)
SHOP_DOMAIN = re.compile(r"^[a-z0-9][a-z0-9\-]*\.myshopify\.com$")
REQUIRED_CLAIMS = ["exp", "nbf", "iss", "dest", "aud", "sub"]
@dataclass
class ShopifySession:
shop: str # my-store.myshopify.com
user_id: str # the "sub" claim
session_id: str | None
claims: dict
def _unauthorized(detail: str) -> HTTPException:
return HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=detail,
headers={"WWW-Authenticate": "Bearer"},
)
def verify_shopify_session(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
) -> ShopifySession:
if credentials is None:
raise _unauthorized("Missing bearer token")
try:
claims = jwt.decode(
credentials.credentials,
settings.shopify_api_secret,
algorithms=["HS256"], # never read this from the token
audience=settings.shopify_api_key,
leeway=10, # seconds of clock skew allowed
options={"require": REQUIRED_CLAIMS},
)
except jwt.ExpiredSignatureError:
raise _unauthorized("Token expired")
except jwt.InvalidAudienceError:
raise _unauthorized("Invalid audience")
except jwt.InvalidTokenError:
raise _unauthorized("Invalid token")
# dest and iss must point at the same, valid Shopify shop
shop = urlparse(claims["dest"]).netloc
issuer_host = urlparse(claims["iss"]).netloc
if not SHOP_DOMAIN.match(shop) or issuer_host != shop:
raise _unauthorized("Invalid shop in token")
return ShopifySession(
shop=shop,
user_id=str(claims["sub"]),
session_id=claims.get("sid"),
claims=claims,
)
Here is what the dependency does. It pulls out the Bearer token and passes it to jwt.decode. It locks the algorithm to HS256, uses your Shopify API key as the expected audience, and lets PyJWT check expiry and not-before for you. Any failure raises an HTTP 401 right away, so a bad request never reaches your route. The extra shop check at the end makes sure iss and dest agree and look like a real myshopify.com domain.
Protecting FastAPI Endpoints
Once the dependency exists, protecting a route is just a matter of adding it to the function signature. FastAPI hands you the decoded session, so you have the merchant context immediately.
from fastapi import APIRouter, Depends, FastAPI
from app.auth.shopify_session import ShopifySession, verify_shopify_session
app = FastAPI()
@app.get("/api/shop")
async def shop_info(session: ShopifySession = Depends(verify_shopify_session)):
return {"shop": session.shop, "user": session.user_id}
# Protect a whole group of routes at once
admin_router = APIRouter(
prefix="/api/admin",
dependencies=[Depends(verify_shopify_session)],
)
@admin_router.get("/settings")
async def get_settings(session: ShopifySession = Depends(verify_shopify_session)):
# FastAPI caches the dependency per request, so the token is verified only once
return {"shop": session.shop, "settings": {}}
app.include_router(admin_router)
On the frontend, App Bridge gives you the token. Send it with every call to your API:
export async function apiFetch(path, options = {}) {
const token = await shopify.idToken(); // always fetch a fresh token
return fetch(path, {
...options,
headers: { ...options.headers, Authorization: `Bearer ${token}` },
});
}Because the shop comes from the verified dest claim, every request is tied to the correct store. That is what blocks cross-tenant data access. Never trust a shop name from a query string or request body. In production you use this shop domain to look up the stored access token or settings for that merchant before you call the Shopify Admin GraphQL API.
Getting an Access Token with Token Exchange
A session token proves who is calling your app. It does not let you call the Admin API. For that you need an access token, and the modern way to get one is token exchange: you trade the session token for an offline access token, with no redirect flow. For more details on building the rest of the application, check out Building Custom Shopify Apps with the Admin GraphQL API.
A session token proves who is calling your app. It does not let you call the Admin API. For that you need an access token, and the modern way to get one is token exchange: you trade the session token for an offline access token, with no redirect flow.
import httpx
from app.config import settings
GRANT = "urn:ietf:params:oauth:grant-type:token-exchange"
ID_TOKEN = "urn:ietf:params:oauth:token-type:id_token"
OFFLINE = "urn:shopify:params:oauth:token-type:offline-access-token"
async def exchange_for_offline_token(shop: str, session_token: str) -> str:
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.post(
f"https://{shop}/admin/oauth/access_token",
json={
"client_id": settings.shopify_api_key,
"client_secret": settings.shopify_api_secret,
"grant_type": GRANT,
"subject_token": session_token,
"subject_token_type": ID_TOKEN,
"requested_token_type": OFFLINE,
},
)
resp.raise_for_status()
return resp.json()["access_token"]
Store the returned access token in your database, encrypted, and keyed by shop. Treat it like a password.
Handling Edge Cases and Expirations
Session tokens are meant to expire fast, usually after 60 seconds. That puts token refresh on the client side. App Bridge asks Shopify for a new token whenever it needs one, so you never build a refresh endpoint.
Clock drift is the one thing that can bite you. If your server clock is a few seconds off, valid tokens can fail the nbf or exp check. Two fixes help: keep the server synced with NTP, and set a small leeway in PyJWT, as I did above with 10 seconds.
Do not store session tokens in a database or cache them. Their whole security model depends on quick expiry and constant re-issuing. A saved token is just a stale credential waiting to be misused. For the same reason, avoid writing full tokens to your logs.
Testing Your Token Verification
Testing against a live embedded app is slow. It is easier to sign your own tokens with PyJWT and run them through the dependency. These tests cover the cases that matter: a good token, an expired one, the wrong audience, the wrong secret, a missing header, and a bad shop.
import os
import time
os.environ.setdefault("SHOPIFY_API_KEY", "test-key")
os.environ.setdefault("SHOPIFY_API_SECRET", "test-secret-with-enough-length-1234")
import jwt
import pytest
from fastapi.testclient import TestClient
from app.config import settings
from app.main import app
client = TestClient(app)
SHOP = "my-store.myshopify.com"
def make_token(secret=None, **overrides):
now = int(time.time())
claims = {
"iss": f"https://{SHOP}/admin",
"dest": f"https://{SHOP}",
"aud": settings.shopify_api_key,
"sub": "42",
"exp": now + 60,
"nbf": now - 5,
"iat": now,
"jti": "abc-123",
"sid": "session-1",
}
claims.update(overrides)
return jwt.encode(claims, secret or settings.shopify_api_secret, algorithm="HS256")
def call(token=None):
headers = {"Authorization": f"Bearer {token}"} if token else {}
return client.get("/api/shop", headers=headers)
def test_valid_token():
res = call(make_token())
assert res.status_code == 200
assert res.json()["shop"] == SHOP
def test_missing_token():
assert call().status_code == 401
def test_expired_token():
old = int(time.time()) - 600
assert call(make_token(exp=old, nbf=old - 60)).status_code == 401
def test_wrong_audience():
assert call(make_token(aud="someone-else")).status_code == 401
def test_wrong_secret():
assert call(make_token(secret="x" * 40)).status_code == 401
def test_bad_shop_domain():
token = make_token(dest="https://evil.example.com", iss="https://evil.example.com/admin")
assert call(token).status_code == 401
def test_malformed_token():
assert call("not.a.jwt").status_code == 401
pytest -q
Common Mistakes to Avoid
- Decoding without verifying. Calling
jwt.decodewithverify_signatureturned off lets anyone forge a token. - Not fixing the algorithm. Always pass
algorithms=["HS256"]. Never trust the algorithm in the token header. - Skipping the audience check. Without it, a token made for a different app could pass.
- Taking the shop from the request. Use the
destclaim only. - Caching or logging tokens. They are short-lived on purpose.
- Confusing session tokens with access tokens. The first identifies the caller, the second calls the Admin API.
Key Takeaways
Verify every Shopify session token yourself with a small FastAPI dependency. Lock the algorithm to HS256, check the audience, require the key claims, and confirm that iss and dest match a real shop. Use the verified shop to scope every query, use token exchange to get Admin API access, and cover the failure cases with tests before you ship.
FAQ
What is a Shopify session token?
It is a short-lived JWT created by App Bridge that proves a merchant is using your embedded app. It is signed with your app client secret and expires in about a minute.
Which algorithm does Shopify use to sign session tokens?
HS256, which is HMAC with SHA-256, using your app client secret as the key.
Do I need a library to verify the token in FastAPI?
You need a JWT library, and PyJWT is a solid pick. You do not need Shopify-specific middleware, because the verification is only a few lines.
Can I use a session token to call the Shopify Admin API?
No. Exchange it for an access token first, then use that token to call the Admin API.
Why do I get "token not yet valid" errors?
Your server clock is probably behind. Sync it with NTP and add a few seconds of leeway in the decode call.
Related posts
Modeling DynamoDB Many to Many Relationships with Adjacency Lists
Learn how to structure many-to-many relationships in DynamoDB using single-table design and adjacency lists for fast, dual-direction querying.
Read articleRotating Secrets in AWS Secrets Manager FastAPI Services
Learn how to fetch, cache, and rotate database credentials dynamically in FastAPI using AWS Secrets Manager and SQLAlchemy without application downtime.
Read articleS3 Presigned URL FastAPI: Secure Client-Side Uploads
Offload file handling from your API. Learn how to generate secure, time-limited S3 presigned URLs in FastAPI using boto3 for direct client uploads.
Read article