-
-
Save tung1404/942ce26cde0680ebe90958a7644211ca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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