[DRF]IsAuthenticated permission 권한 확인 token 인증 방식으로 변경하기

Jay·2022년 9월 16일
0

나는 로그아웃 기능을 구현하면서 로그인된 유저만 로그아웃 api에 접근할 수 있도록 제한하려고 하였다. API 접근 권한을 설정하기위해 rest_framework.permissions의 IsAuthenticated 권한을 사용하였지만 DRF의 Default authentication class는 세션 기반으로 이루어진다. 따라서 request를 보낼때 발급받은 token을 헤더의 Authorization 키로 보냈음에도 인증이 제대로 이루어지지 않았다.

rest_framework.permissions의 IsAuthenticated의 검증 방식은 요청을 보낸 사용자의 인증 여부를 확인하는 방식이지 헤더의 Authroization value를 확인하여 검증하는 방식이 아니다. API의 접근을 token 검증 방식으로 변경하기 위해서는 우선 DRF의 기본 인증 방식을 바꿔주어야 한다.



모듈 설치 및 설정

사용할 Authentication class는 dj_rest_auth.jwt_auth 모듈의 JWTcookieAuuthentication 클래스이다. 해당 모듈을 사용하기 위해 먼저 설치한 후 installed apps에 추가해주었다.

pip install dj-rest-auth
THIRD_PARTIES = [
    'rest_framework',
    'rest_framework_simplejwt',
    'rest_framework_simplejwt.token_blacklist',
    'rest_framework.authtoken',
    'dj_rest_auth',
]

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
] + THIRD_PARTIES

그리고 기본 authentication 방식을 설정하기 위해 rest framework 설정에서 default authentication classes를 설치한 JWTCookieAuthentication으로 변경해주었다.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES' : [
        'dj_rest_auth.jwt_auth.JWTCookieAuthentication'
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ]
}

그 다음 포스트맨으로 permission_classes가 IsAuthenticated인 logout API로 Authorization 헤더에 아무값이나 입력후 요청을 보내보았다.

{
    "detail": "Given token not valid for any token type",
    "code": "token_not_valid",
    "messages": [
        {
            "token_class": "AccessToken",
            "token_type": "access",
            "message": "Token is invalid or expired"
        }
    ]
}

기존의 응답과는 다른 주어진 토큰값이 유효하지 못하다는 응답을 받았다. 유저 검증 방식이 token으로 바뀐것을 확인할 수 있었다. 그 다음 유효한 token값과 함께 api에 요청을 보내니 올바르게 로그아웃 처리가 된 것을 확인할 수 있었다.

0개의 댓글