Sanic JWT

1.8.0 · active · verified Thu Apr 16

Sanic-JWT provides a JWT (JSON Web Token) authentication flow for the Sanic web framework. It simplifies the process of user authentication, token generation, and securing endpoints. The library is currently at version 1.8.0, with releases focused on compatibility with newer Sanic and PyJWT versions, and feature enhancements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `sanic-jwt` with a Sanic application. It includes a simple authentication function, a protected route using the `@protected()` decorator, and a public route. Users obtain a JWT by POSTing to the `/auth` endpoint with credentials, and then use this token in the `Authorization: Bearer` header for protected routes.

from sanic import Sanic, response
from sanic_jwt import SanicJWT, protected
import os

app = Sanic("my_jwt_app")

# Set a secret key for JWT signing. Crucial for security.
app.config.SANIC_JWT_SECRET = os.environ.get("SANIC_JWT_SECRET", "your-super-secret-key-that-no-one-knows")

# Define an asynchronous authentication function.
# This function handles both token verification (payload present) and user login (payload None).
async def authenticate(request, payload):
    if payload: # Token verification for protected routes
        # In a real app, you'd fetch user data from a DB based on payload (e.g., user_id)
        user_id = payload.get("user_id")
        if user_id:
            return {"user_id": user_id, "username": payload.get("username", "user")} # Return user info for ctx
        return False
    else: # User login attempt for the /auth endpoint
        # Expect username/password in request.json
        username = request.json.get("username")
        password = request.json.get("password")

        if username == "test" and password == "test": # Dummy check
            return {"user_id": 1, "username": "testuser"} # Return user info to be included in JWT payload
        return False # Authentication failed

# Initialize Sanic-JWT with the app and your custom authentication function.
SanicJWT.setup(app, authenticate=authenticate)

@app.route("/protected")
@protected()
async def protected_route(request):
    # Access user data via request.ctx.user after successful authentication
    username = request.ctx.user.get('username', 'authenticated user')
    return response.json({"message": f"Hello, {username}! This is a protected route."})

@app.get("/public")
async def public_route(request):
    return response.json({"message": "This is a public route, accessible without a token."})

if __name__ == "__main__":
    # To run:
    # 1. Start the app: python your_script_name.py
    # 2. Login (obtain token): curl -X POST -H "Content-Type: application/json" -d '{"username":"test","password":"test"}' http://localhost:8000/auth
    # 3. Access protected route with token: curl -H "Authorization: Bearer <your_token_here>" http://localhost:8000/protected
    app.run(host="0.0.0.0", port=8000, debug=True)

view raw JSON →