나는 djangorestframework-simplejwt 만료 를 이해하려고 노력하고 있으며 토큰이 만료되면 무엇이 반환되는지 알고 싶습니다.
이것을 탐구하기 위해 내 django 프로젝트에서 간단한 테스트 케이스를 작성했지만 만료가 발생하지 않는 것 같습니다.
views.py
import json
from http import HTTPStatus
from django.http import JsonResponse
from rest_framework.decorators import api_view
from .models import Visitor
@api_view(["POST"])
def visitor_post(request):
body_unicode = request.body.decode("utf-8")
if not body_unicode.strip():
return JsonResponse({"status": HTTPStatus.BAD_REQUEST}, status=HTTPStatus.BAD_REQUEST)
body = json.loads(body_unicode)
submitted_datetime = body["submitted_datetime"]
visitor = Visitor(
representative_name=body["representative_name"],
visitor_type=body["visitor_type"],
visitor_count=body["visitor_count"],
submitted_datetime=submitted_datetime,
)
visitor.save()
return JsonResponse({"status": HTTPStatus.CREATED}, status=HTTPStatus.CREATED)
현재 내 테스트 케이스는 다음과 같습니다.
tests.py
import datetime
import json
from time import sleep
from http import HTTPStatus
from typing import Optional, Tuple
from accounts.models import CustomUser
from django.urls import reverse
from django.utils import timezone
from django.test import override_settings
from rest_framework.test import APIClient, APITestCase
EXPIRE_WAIT_SECONDS = 5
SIMPLE_JWT_EXPIRE_TEST_SETTINGS = {
"ACCESS_TOKEN_LIFETIME": datetime.timedelta(seconds=EXPIRE_WAIT_SECONDS),
"REFRESH_TOKEN_LIFETIME": datetime.timedelta(days=14),
"ROTATE_REFRESH_TOKENS": True,
"BLACKLIST_AFTER_ROTATION": False,
"ALGORITHM": "HS256",
"SIGNING_KEY": 'kkdkasjf;a',
"VERIFYING_KEY": None,
"AUTH_HEADER_TYPES": ("JWT",),
"USER_ID_FIELD": "id",
"USER_ID_CLAIM": "user_id",
"AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
"TOKEN_TYPE_CLAIM": "token_type",
}
class ViewsTestCase(APITestCase):
def setUp(self):
self.valid_user = CustomUser(last_name="user", first_name="valid", username="validuser", email="[email protected]")
self.valid_user_password = "mysecretpassword"
self.valid_user.set_password(self.valid_user_password)
self.valid_user.save()
self.apiclient = APIClient()
def _get_jwt_token(self, username: Optional[str] = None, password: Optional[str] = None) -> Tuple[str, str]:
if not username:
username = self.valid_user.username
if not password:
password = self.valid_user_password
body = {"username": username, "password": password}
url = reverse("token_obtain_pair")
response = self.apiclient.post(url, data=body, format="json")
self.assertEqual(response.status_code, 200)
token_data = json.loads(response.content)
return token_data["access"], token_data["refresh"]
@override_settings(SIMPLE_JWT=SIMPLE_JWT_EXPIRE_TEST_SETTINGS)
def test_visitor_post_token_expire(self):
access_token, _ = self._get_jwt_token()
now = timezone.now()
data = {
"representative_name": "Somename",
"visitor_count": 1,
"submitted_datetime": now.isoformat(),
}
sleep(EXPIRE_WAIT_SECONDS + 1)
self.apiclient.credentials(HTTP_AUTHORIZATION=f"JWT {access_token}")
url = "/visitors/"
response = self.apiclient.post(url, data=data, format="json")
self.assertEqual(response.status_code, HTTPStatus.UNAUTHORIZED)
이로 인해 일종의 권한 부여 오류가 발생할 것으로 예상 401
하지만 여전히 보호 된 뷰를 생성하는 것 같습니다.
self.assertEqual (response.status_code, HTTPStatus.UNAUTHORIZED) AssertionError : 201! = HTTPStatus.UNAUTHORIZED : 401
토큰이 만료되지 않는 이유는 무엇입니까? 또는 토큰이 만료되도록하려면 어떻게해야합니까?
아마도 나는 이것을 올바르게 이해하지 못할 것입니다.
내 이해는 ACCESS_TOKEN_LIFETIME
만료되면 더 이상을 사용할 수 없으며 access_token
토큰을 사용하여 새 토큰을 받아야합니다 refresh
. 그 맞습니까?
플러그인은 설정을 가져와 부팅시 개체를 인스턴스화해야합니다. 런타임에 설정을 다시 읽지 않으므로 재정의하는 것은 쓸모가 없습니다.
당신이했던 것처럼,이 기능을 테스트하는 적절한 방법은 테스트를위한 별도의 설정 모듈을 가지고 거기에 플러그인 설정을 두는 것입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다