Skip to content

Instantly share code, notes, and snippets.

@cho0h5
Created June 11, 2022 03:27
Show Gist options
  • Save cho0h5/5796040fe29ca98247e83129d89491cb to your computer and use it in GitHub Desktop.
Save cho0h5/5796040fe29ca98247e83129d89491cb to your computer and use it in GitHub Desktop.
# Reference: https://indominusbyte.github.io/fastapi-jwt-auth/usage/basic/
from fastapi import FastAPI, Depends, Request, HTTPException
from fastapi.responses import JSONResponse
from fastapi_jwt_auth import AuthJWT
from fastapi_jwt_auth.exceptions import AuthJWTException
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
username: str
password: str
class Settings(BaseModel):
authjwt_secret_key: str = "secret"
@AuthJWT.load_config
def get_config():
return Settings()
@app.exception_handler(AuthJWTException)
def authjwt_exception_handler(request: Request, exc: AuthJWTException):
return JSONResponse(
status_code = exc.status_code,
content = {"detail": exc.message}
)
@app.get("/")
def read_root():
return {"Hello": "world"}
@app.post("/login")
def login(user: User, Authorize: AuthJWT = Depends()):
if user.username != "test" or user.password != "test":
raise HTTPException(status_code=401, detail="Bad username or password")
access_token = Authorize.create_access_token(subject=user.username)
return {"access_token": access_token}
@app.get("/user")
def user(Authorize: AuthJWT = Depends()):
Authorize.jwt_required()
current_user = Authorize.get_jwt_subject()
return {"user": current_user}
# $ curl -H "Content-Type: application/json" -X POST \
# -d '{"username":"test", "password":"test"}' http://localhost:8081/login
# $ export TOKEN=eyJ0.....
# $ curl -H "Authorization: Bearer $TOKEN" http://localhost:8081/user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment