μκΈ°λ₯ #51
μ§νμ€μκΈ°λ₯ #44: π Mangement Cloud server FastAPI νλ‘μ νΈ
π₯ Epic 1 - Task (Auth Extension) π§βπ» /me & /logout ꡬν
0%
μ€λͺ
π₯ Epic 1 β Task (Auth Extension)¶
π§βπ» /me & /logout ꡬν¶
π μμ κ°μ¶
λ‘κ·ΈμΈ κΈ°λ₯μ νμ₯νμ¬
-
νμ¬ λ‘κ·ΈμΈν μ¬μ©μ μ 보λ₯Ό λ°ννλ /me
-
ν΄λΌμ΄μΈνΈ μΈ‘μμ ν ν°μ νκΈ°νλ /logout
APIλ₯Ό ꡬννλ€.
μ΄ λ κΈ°λ₯μ DB μ°κ²° μμ΄λ JWTλ§μΌλ‘ ν μ€νΈ κ°λ₯νλ€.
π οΈ 1. JWT μΈμ¦ λ―Έλ€μ¨μ΄ λ§λ€κΈ°¶
π app/core/auth.py
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from app.core.jwt import SECRET_KEY, ALGORITHM
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
def get_current_user(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise HTTPException(status_code=401, detail="Invalid token")
return username
except JWTError:
raise HTTPException(status_code=401, detail="Invalid or expired token")
π DB μμ΄λ usernameμ JWTμμ λ°λ‘ κΊΌλΌ μ μμ
π οΈ 2. /me API ꡬν¶
π app/routers/auth.pyμ μΆκ°
@router.get("/me")
def me(current_user: str = Depends(get_current_user)):
return {"username": current_user}
π JWTλ§ μμΌλ©΄ λ°λ‘ ν
μ€νΈ κ°λ₯
π DB μ°κ²° νμ μμ
π οΈ 3. /logout API ꡬν¶
FastAPIλ μλ²μμ JWTλ₯Ό κ°μ λ‘ λ¬΄ν¨νν μ μλ€.
JWTλ βμλ²κ° κΈ°μ΅νμ§ μλ ν ν°βμ΄κΈ° λλ¬Έ.
κ·Έλμ μΌλ°μ μΈ λ°©μμ:
β ν΄λΌμ΄μΈνΈκ° ν ν°μ λ²λ¦¬λ λ°©μ
β /logoutμ κ·Έλ₯ βμ±κ³΅βλ§ λ°ννλ©΄ λ¨.
@router.post("/logout")
def logout():
return {"detail": "Logged out. Please delete your token on client side."}
π ν΄λΌμ΄μΈνΈ(PWA, μ±, μΉ)μμ ν ν°μ μμ νλ©΄ λ‘κ·Έμμ μλ£
π μλ²λ ν ν°μ μ μ₯νμ§ μκΈ° λλ¬Έμ β무ν¨νβλΌλ κ°λ μ΄ μμ
π§ͺ 4. test_main.http ν μ€νΈ¶
DB μμ΄λ λ°λ‘ ν μ€νΈ κ°λ₯
### Login (DB μ°κ²° ν ν
μ€νΈ)
POST http://127.0.0.1:8000/login
Content-Type: application/json
{
"username": "admin",
"password": "1234"
}
### Me Test
GET http://127.0.0.1:8000/me
Authorization: Bearer {{token}}
### Logout Test
POST http://127.0.0.1:8000/logout
π μ°μΆλ¬Ό
-
JWT μΈμ¦ λ―Έλ€μ¨μ΄ (get_current_user)
-
/me API ꡬν
-
/logout API ꡬν
-
DB μμ΄λ ν μ€νΈ κ°λ₯ν μΈμ¦ νλ¦ μμ±
νμν λ°μ΄ν°κ° μμ΅λλ€.