I am learning DJANGO REST API. I have decided to use Simple JWT
. My source is https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html#installation
So in **settings*
* i put :
from datetime import timedelta
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_FILTER_BACKENDS':(
'rest_framework.filters.SearchFilter',
'rest_framework.filters.OrderingFilter',
),
'SEARCH_PARAM':'search',
'ORDERING_PARAM':'ordering',
}
JWT_AUTH = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
'UPDATE_LAST_LOGIN': True,
'AUTH_HEADER_TYPES': ('Bearer',),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
in urls :
from django.contrib import admin
from django.urls import path,include
from rest_framework_simplejwt.views import (TokenObtainPairView,TokenRefreshView,)
urlpatterns = [
path('admin/', admin.site.urls),
path('api/auth/jwt/', TokenObtainPairView.as_view()),
path('api/auth/jwt/refresh/', TokenRefreshView.as_view()),
path('api/status/', include('status.api.urls'))
]
and in views.py
:
from rest_framework import generics, mixins, permissions
from rest_framework.authentication import SessionAuthentication
from rest_framework.views import APIView
from rest_framework.response import Response
import json
from django.shortcuts import get_object_or_404
from status.models import Status
from .serializers import StatusSerializer
def is_json(json_data):
try:
real_json = json.loads(json_data)
is_valid = True
except ValueError:
is_valid = False
return is_valid
class StatusDetailAPIView(generics.RetrieveAPIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = StatusSerializer
queryset = Status.objects.all()
lookup_field='id'
class StatusAPIView(mixins.RetrieveModelMixin,generics.ListAPIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = StatusSerializer
passed_id= None
search_fields = ('user__username','content')
queryset = Status.objects.all()
def perform_create (self,serializer):
serializer.save(user=self.request.user)
in my scripts/rest_framework_api.py
:
import requests
import json
AUTH_ENDPOINT = "http://127.0.0.1:8000/api/auth/jwt/"
REFRESH_ENDPOINT = AUTH_ENDPOINT "refresh/"
ENDPOINT="http://127.0.0.1:8000/api/status/"
headers = { "Content-Type": "application/json" }
data = {
'username':'lulu',
'password':'lulu'
}
r = requests.post(AUTH_ENDPOINT,data=json.dumps(data),headers=headers)
token = r.json()['access']
refresh_data = { 'refresh': r.json()['refresh'] }
new_response = requests.post(REFRESH_ENDPOINT,data=json.dumps(refresh_data),headers=headers)
new_token = new_response.json()
print(new_token)
So print(new_token
) return 'access' rather than 'refresh'.
What I do wrong that it does not return 'refresh' ?
Would appreciate for your insight/help to fix it.
CodePudding user response:
The error response of the API endpoint /api/auth/jwt/refresh/
means that you need to put refresh token to the refresh
field (not token
field) of POST request body in your client test code, the path /api/auth/jwt/refresh/
is resolved internally to TokenRefreshView which uses TokenRefreshSerializer for input validation and the serializer does require refresh
field.