FastAPI JWT Extended


1. Simple JWT Token Generation:

from fastapi import FastAPI, Body
from fastapi.responses import JSONResponse
from fastapi_jwt_extended import create_access_token

app = FastAPI()

@app.post("/login")
async def login(username: str = Body(...), password: str = Body(...)):
    if username == "admin" and password == "secret":
        return JSONResponse(content={"token": create_access_token(identity=username)})
    return JSONResponse(content={"error": "Invalid credentials"}, status_code=401)

2. JWT Token with Custom Claims:

from fastapi import FastAPI, Body
from fastapi.responses import JSONResponse
from fastapi_jwt_extended import create_access_token, get_jwt_current_user

app = FastAPI()

@app.post("/login")
async def login(username: str = Body(...), password: str = Body(...)):
    if username == "admin" and password == "secret":
        return JSONResponse(content={"token": create_access_token(identity=username, claims={"role": "admin"})})
    return JSONResponse(content={"error": "Invalid credentials"}, status_code=401)

@app.get("/protected")
async def protected_route():
    current_user = get_jwt_current_user()
    return JSONResponse(content={"user": current_user})

3. JWT Token Refresh:

4. JWT Token Blacklist:

5. JWT Token with HTTPOnly Cookies:

6. JWT Token with HTTPS Only:

7. JWT Token with Multiple Tokens:

8. JWT Token with Multiple Endpoints:

9. JWT Token with Rate Limiting:

10. JWT Token with Auto-Decoding:

11. JWT Token with Multiple Decoders:

12. JWT Token with Refresh Tokens:

13. JWT Token with User-Specific Keys:

14. JWT Token with Multiple Claims Sets: