Protect a Python API (Flask)
Add OneiD to a Python API API with PyJWT with Flask, step by step.
This quickstart adds OneiD to a api with PyJWT with Flask. Every file is complete and runs as it is.
Tip Using an AI coding agent? Give it this page as Markdown (add
.mdto the address) together with the Connector specification. See Build with AI coding agents.
Before you start
- A OneiD address, for example
https://YOUR_ONEID. The code below uses the demonstration instancehttps://auth.oltinid.com; replace it with your own. - An access token with the scope
orders.readto test with.
1. Register the application
An API is not a client: it does not sign in. It needs an API scope that clients can request.
- Ask your OneiD administrator to create the API scope
orders.read(or a scope named after your API) in the admin console. - Ask for the scope to be allowed on the client that will call the API.
- Get an access token with that scope: from a server or browser application, or with the client credentials grant.
Note OneiD access tokens have no
audclaim. The API accepts a token because it was issued by your OneiD, is unexpired and carries the scope the API requires. Give each API its own scopes. See Protect an API.
2. Install
pip install flask "pyjwt[crypto]"
3. Add the code
app.py
import json
from urllib.request import urlopen
import jwt
from flask import Flask, abort, jsonify, request
app = Flask(__name__)
# Reads the issuer name and the address of the signing keys from OneiD.
with urlopen("https://auth.oltinid.com/.well-known/openid-configuration") as response:
oneid = json.load(response)
# PyJWKClient downloads the public keys and finds the key that signed a token.
keys = jwt.PyJWKClient(oneid["jwks_uri"])
def check_token(scope):
"""Returns the claims of the access token, or stops the request with 401 or 403."""
kind, _, token = request.headers.get("Authorization", "").partition(" ")
if kind != "Bearer":
abort(401)
try:
# Checks the signature, the issuer and the expiry. No audience: OneiD tokens have no aud claim.
claims = jwt.decode(
token,
keys.get_signing_key_from_jwt(token).key,
algorithms=["RS256"],
issuer=oneid["issuer"],
options={"require": ["exp", "iss", "sub"]},
)
except jwt.PyJWTError:
abort(401)
# The scope claim is one string with a space between the scopes.
if scope not in claims.get("scope", "").split():
abort(403)
return claims
@app.route("/orders")
def orders():
claims = check_token("orders.read")
return jsonify(sub=claims["sub"])
if __name__ == "__main__":
app.run(host="localhost", port=4000)
4. Run it
Run: python app.py.
The API listens on http://localhost:4000. GET /orders answers 401 without a valid token, 403 without the scope orders.read, and otherwise returns the sub of the caller.
Test it with a token:
curl -i http://localhost:4000/orders
# HTTP/1.1 401 Unauthorized
curl -i http://localhost:4000/orders -H "Authorization: Bearer $ACCESS_TOKEN"
# HTTP/1.1 200 OK when the token carries orders.read, 403 when it does not
Checkpoint Without a token the API answers 401. With a valid token that carries
orders.readit answers 200 and returns yoursub; with a valid token without that scope it answers 403.
Common issues
- 401 with a token that looks valid. Check the issuer: OneiD’s issuer ends with a slash (
https://YOUR_ONEID/). - The API checks
audand rejects every token. OneiD access tokens carry noaud; remove the audience check and check the scope instead. - More errors and fixes: Errors and troubleshooting.