Skip to content

Commit cca2a18

Browse files
authored
Merge pull request #10 from RJihyeon/fe/api
fix: backend 로그인 로직 수정
2 parents 7c091fb + 45ad4cb commit cca2a18

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

backend/app/api/auth_router.py

+34-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from typing import Annotated
22

3-
from fastapi import APIRouter, HTTPException, Depends
3+
from fastapi import APIRouter, HTTPException, Depends, Response, Request
44
from fastapi.responses import RedirectResponse
55

66
from auth import JwtAuth, request_access_token, request_user_info
@@ -32,6 +32,7 @@ async def login() -> RedirectResponse:
3232

3333
@router.get("/authenticate")
3434
async def auhtenticate(
35+
response : Response,
3536
user_repo: Annotated[UserRepository, Depends(get_user_repository)],
3637
code: str | None = None,
3738
error: str | None = None,
@@ -71,5 +72,35 @@ async def auhtenticate(
7172
raise Exception("user id must not be None")
7273

7374
# 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}"}

backend/readme.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ pipenv run python ./backend/app/main.py
1313
1414
실행후 ...
1515
16-
docker-compose downv -v
16+
docker-compose down -v
1717
```
1818

1919
## 테스트방법

0 commit comments

Comments
 (0)