본문 바로가기
C.W.K.
Stream
Lesson 08 of 08 · published

인증

~13 min · fastapi, auth, jwt, depends

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

인증은 accept() 전에 끝내

핸드셰이크는 클라이언트를 ‘열렸다가 곧바로 닫히는’ 어색한 상태에 두지 않고 거절할 유일한 자리야. 토큰 검증, 권한 확인, 사용자별 속도 제한 같은 모든 인증을 websocket.accept() 전에 끝내. 엄격히 처리하면 연결 비용이 0이지만 느슨하게 처리하면 인증 상태가 새고 클라이언트 경험도 혼란스러워져.

FastAPI Depends 는 WebSocket 에서도 작동해

Depends(...) 체계는 WebSocket 엔드포인트에서도 완전히 지원돼. 토큰을 꺼내 검증하는 의존성을 만들고 실패할 때 WebSocketException 을 일으키면 프레임워크가 연결 종료를 처리해 줘.

쿠키와 토큰

브라우저 사용자가 세션 쿠키로 인증했다면 쿠키는 WebSocket 프로토콜 전환 GET 요청에 자동으로 실려. websocket.cookies 에서 읽으면 돼. 모바일이나 서버 간 통신 같은 비브라우저 클라이언트는 쿼리 문자열에 토큰을 넣어. cwkPippa 도 WebUI 에는 쿠키, 도구에는 토큰을 쓰면서 같은 인증 코드 경로를 서로 다른 운반 방식으로 공유해.

Code

WebSocket 에서 Depends 방식으로 인증하기·python
from fastapi import WebSocket, WebSocketException, status, Depends

async def get_current_user(websocket: WebSocket) -> dict:
    token = websocket.query_params.get('token')
    if not token:
        raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
    user = decode_jwt(token)
    if not user:
        raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
    return user

@app.websocket('/ws')
async def protected(
    websocket: WebSocket,
    user: dict = Depends(get_current_user),
):
    await websocket.accept()
    await websocket.send_json({'type': 'welcome', 'data': {'user': user['name']}})
    # ... handler
쿠키 기반 인증(브라우저 세션)·python
@app.websocket('/ws')
async def cookie_auth(websocket: WebSocket):
    session_id = websocket.cookies.get('session_id')
    user = await load_session(session_id) if session_id else None
    if user is None:
        await websocket.close(code=4001, reason='unauthorized')
        return
    await websocket.accept()
    # ... user is the same shape as your REST auth produces

External links

Exercise

Depends 패턴으로 /ws/{room} 엔드포인트를 만들어. (a) 토큰이 유효한 사용자로 해석되는지, (b) 사용자에게 방 읽기 권한이 있는지, (c) 쓰기에는 쓰기 권한이 있는지 검사해. 전체 권한, 읽기 전용, 접근 불가 사용자로 시험해 각각 다른 코드 경로를 타는지 확인해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.