1
1
from typing import Annotated
2
2
3
- from fastapi import APIRouter , HTTPException , Depends
3
+ from fastapi import APIRouter , HTTPException , Depends , Response , Request
4
4
from fastapi .responses import RedirectResponse
5
5
6
6
from auth import JwtAuth , request_access_token , request_user_info
@@ -32,6 +32,7 @@ async def login() -> RedirectResponse:
32
32
33
33
@router .get ("/authenticate" )
34
34
async def auhtenticate (
35
+ response : Response ,
35
36
user_repo : Annotated [UserRepository , Depends (get_user_repository )],
36
37
code : str | None = None ,
37
38
error : str | None = None ,
@@ -71,5 +72,35 @@ async def auhtenticate(
71
72
raise Exception ("user id must not be None" )
72
73
73
74
# TODO: expire and path
74
- access_jwt = JwtAuth .create_token (user .id )
75
- return JwtResponse (access_token = access_jwt )
75
+ jwt_token = JwtAuth .create_token (user .id )
76
+
77
+ # 5. JWT를 HttpOnly 쿠키에 저장
78
+ response .set_cookie (
79
+ key = "access_token" , # 쿠키 이름
80
+ value = jwt_token , # JWT 토큰 값
81
+ httponly = True , # HttpOnly 속성 (JS에서 접근 불가)
82
+ secure = False , # HTTPS 환경에서 True로 설정
83
+ samesite = "Lax" , # CSRF 방지
84
+ max_age = 3600 , # 쿠키 만료 시간 (초)
85
+ )
86
+
87
+ # 6. 프론트엔드 대시보드로 리디렉션
88
+ return RedirectResponse (url = "http://localhost:8001" )
89
+
90
+
91
+
92
+ @router .get ("/protected-data" )
93
+ async def protected_data (request : Request ):
94
+ # 쿠키에서 JWT 가져오기
95
+ token = request .cookies .get ("access_token" )
96
+ if not token :
97
+ raise HTTPException (status_code = 401 , detail = "Unauthorized" )
98
+
99
+ # JWT 검증
100
+ try :
101
+ payload = JwtAuth .verify_token (token )
102
+ user_id = payload .get ("user_id" )
103
+ except Exception as e :
104
+ raise HTTPException (status_code = 401 , detail = f"Invalid token: { str (e )} " )
105
+
106
+ return {"message" : f"Hello, User { user_id } " }
0 commit comments