from fastapi import FastAPI, Body, Cookie, HTTPException
from fastapi.responses import JSONResponse
from fastapi_jwt_extended import create_access_token, create_refresh_token, get_jwt_current_user, get_jwt
from fastapi_jwt_extended.exceptions import TokenExpiredError, InvalidTokenError
app = FastAPI()
@app.post("/login")
async def login(username: str = Body(...), password: str = Body(...)):
if username == "admin" and password == "secret":
access_token = create_access_token(identity=username)
refresh_token = create_refresh_token(identity=username)
return JSONResponse(content={"access_token": access_token, "refresh_token": refresh_token})
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})
@app.get("/refresh")
async def refresh_token(refresh_token: str = Cookie(...)):
try:
current_user = get_jwt_current_user(refresh_token=refresh_token)
new_access_token = create_access_token(identity=current_user.identity)
# Set the refresh token as a cookie
response = JSONResponse(content={"access_token": new_access_token})
response.set_cookie(key="refresh_token", value=refresh_token, httponly=True)
return response
except TokenExpiredError:
raise HTTPException(status_code=401, detail="Refresh token expired")
except InvalidTokenError:
raise HTTPException(status_code=401, detail="Invalid refresh token")