토큰 기반 권한별 기능 제한 아르켜줄게

sein lee·4일 전
0

project

목록 보기
4/4

History

개발 중인 프로젝트에서 로그인 권한별로 기능을 제한하기로 했다.(당연한 기능이긴 함)

FastAPI를 사용하여 토큰 기반으로 사용자의 권한을 체크하고 특정 권한만 삭제, 수정 등이 가능하도록 구현하기로 했다.

Solve

1. 클라이언트 -> 서버

  • 사용자는 로그인 후 서버에서 발급한 token 을 쿠키에 저장하고
    API요청 시 쿠키를 포함하여 요청을 보냄

2. 서버-> 토큰인증

  • request.cookies.get("token") 을 사용해 쿠키에서 토큰을 가져옴.
  • util_authentication.authentication("/clsf/delete", token) 을 호출해 토큰을 검증하고 사용자 정보(userId, role)를 추출.

3. Role 확인 후 기능 제한

  • <util_authentication.py>
    -> JWT토큰을 디코딩해서 사용자 정보 추출 코드
    -> JWT 토큰을 HS256 알고리즘을 사용하여 검증
import os
from typing import Any, Dict, Optional, Union
import jwt
from fastapi_base.web.response_base import Result, SodaflowResponseBase

# ENV_EMAIl 을 가져오는데 없다면 aaa@gmail.com로
ENV_EMAIl = os.getenv('ENV_EMAIl', 'aaa@gmail.com')
ENV_EMAIL_ENCODE = ENV_EMAIl.encode()
#util_authentication.ENV_EMAIl.encode()
ALGORITHM = "HS256"

checkedRole = [
    { 'endpoint': "/clsf/delete/", 'roles': ['000', '001', '002'] },
]

def authentication(
    endpoint: str, token: Optional[str]
) -> Union[SodaflowResponseBase[None], SodaflowResponseBase[Dict[str, Any]]]:
    failed_result = SodaflowResponseBase[None](
        data=None, result=Result(code=-1, message="Permission is denied.")
    )
    if token is None:
        return failed_result

    data: Dict[str, Any] = jwt.decode(
        token, ENV_EMAIL_ENCODE, algorithms=[ALGORITHM]
    )

    # checkedRole 리스트를 순회하여 endpoint 찾기
    for role in checkedRole:
        if role["endpoint"] == endpoint:
            # endpoint가 일치하면 roles 배열 안에 data['role']이 있는지 확인
            if data["role"] in role["roles"]:
                return SodaflowResponseBase(
                    data=data,
                    result=Result(
                        code=0, message="Authentication successful."
                    ),
                )

    return failed_result

4. 제한 조건 만족 시 기능 실행

  • delete_clsf_service() 호출
profile
개발감자

0개의 댓글

관련 채용 정보