C.W.K.
Stream
Lesson 08 of 08 · published

Authentication

~13 min · fastapi, auth, jwt, depends

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

Auth 는 accept() 전에 완료

Handshake 가 클라를 'open then immediately closed' 의 어색한 상태 안 두고 reject 할 수 있는 유일한 자리. 그래서 모든 auth — token validation, permission 체크, user-별 rate limit — 는 websocket.accept() 전에. 빡세게 굴면 비용 0; 느슨하면 leaked auth state 와 헷갈리는 클라 UX.

FastAPI Depends 가 WebSocket 에서도 작동

Depends(...) 시스템이 WebSocket endpoint 에서 완전 지원. token 추출 + validation 의존성 짜고, 실패 시 WebSocketException raise 하면, framework 가 close 처리.

Cookie vs token

브라우저에서 user 가 session cookie 로 인증하면, cookie 가 WebSocket upgrade GET 에 자동 동봉. websocket.cookies 로 읽어. non-browser 클라 (모바일, server-to-server) 는 query string 에 token 넘겨. cwkPippa 가 WebUI 엔 cookie, tooling 엔 token — 같은 auth code path, 다른 transport.

Code

WebSocket 에 Depends-style auth·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
Cookie-based auth (브라우저 session)·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} endpoint 짜: (a) token 이 valid user 로 decode, (b) user 가 room read 권한, (c) write 는 write 권한. 세 user (full, read-only, no access) 로 테스트, 각자 다른 code path 히트.

Progress

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

댓글 0

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

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