|
| 1 | +from fastapi import FastAPI, HTTPException, Depends, Request |
| 2 | +from fastapi.responses import JSONResponse |
| 3 | +from fastapi_jwt_auth import AuthJWT |
| 4 | +from fastapi_jwt_auth.exceptions import AuthJWTException |
| 5 | +from pydantic import BaseModel |
| 6 | + |
| 7 | +app = FastAPI() |
| 8 | + |
| 9 | +class User(BaseModel): |
| 10 | + username: str |
| 11 | + password: str |
| 12 | + |
| 13 | +class Settings(BaseModel): |
| 14 | + authjwt_secret_key: str = "secret" |
| 15 | + |
| 16 | +@AuthJWT.load_config |
| 17 | +def get_config(): |
| 18 | + return Settings() |
| 19 | + |
| 20 | +@app.exception_handler(AuthJWTException) |
| 21 | +def authjwt_exception_handler(request: Request, exc: AuthJWTException): |
| 22 | + return JSONResponse( |
| 23 | + status_code=exc.status_code, |
| 24 | + content={"detail": exc.message} |
| 25 | + ) |
| 26 | + |
| 27 | +@app.post('/login') |
| 28 | +def login(user: User, Authorize: AuthJWT = Depends()): |
| 29 | + if user.username != "test" or user.password != "test": |
| 30 | + raise HTTPException(status_code=401,detail="Bad username or password") |
| 31 | + |
| 32 | + # You can be passing custom claim to argument user_claims |
| 33 | + # in function create_access_token() or create refresh token() |
| 34 | + another_claims = {"foo": ["fiz","baz"]} |
| 35 | + access_token = Authorize.create_access_token(subject=user.username,user_claims=another_claims) |
| 36 | + return {"access_token": access_token} |
| 37 | + |
| 38 | +# In protected route, get the claims you added to the jwt with the |
| 39 | +# get_raw_jwt() method |
| 40 | +@app.get('/claims') |
| 41 | +def user(Authorize: AuthJWT = Depends()): |
| 42 | + Authorize.jwt_required() |
| 43 | + |
| 44 | + foo_claims = Authorize.get_raw_jwt()['foo'] |
| 45 | + return {"foo": foo_claims} |
0 commit comments