Reputation: 321
I am creating a web application with react-js using redux and back-end with python django with django rest framework.
for authentication I am using JWT.
The problem I am facing is when sending request from front-end getting error as 403.
I have checked the backend side all the configuration are set but still getting this error.
Please check the below code.
Model:
class StatusQuerySet(models.QuerySet):
pass
class StatusManager(models.Manager):
def get_queryset(self):
return StatusQuerySet(self.model,using=self._db)
class Apptype(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
appType = models.CharField(max_length=50)
objects = StatusManager()
def __str__(self):
return self.appType
Serializer:
class AppTypeSeriializer(serializers.ModelSerializer):
class Meta:
model = Apptype
fields = [
'user',
'id',
'appType'
]
read_only_fields = ['user','id']
views
class AppTypeStatusAPIDetailView(
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.RetrieveAPIView):
lookup_field = 'id'
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = AppTypeSeriializer
queryset = Apptype.objects.all()
def put(self,request, *args, **kwargs):
print("Value of = ",request.data.get("appType"))
return self.update(request, *args, **kwargs)
def patch(self,request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self,request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
URL
urlpatterns = [
url(r'^appType/$',AppTypeStatusView.as_view()),
url(r'^appType/(?P<id>\d+)/$',AppTypeStatusAPIDetailView.as_view()),
]
Permissions
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
JWT_AUTH = {
'JWT_ENCODE_HANDLER':
'rest_framework_jwt.utils.jwt_encode_handler',
'JWT_DECODE_HANDLER':
'rest_framework_jwt.utils.jwt_decode_handler',
'JWT_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_payload_handler',
'JWT_PAYLOAD_GET_USER_ID_HANDLER':
'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'JWT',
'JWT_AUTH_COOKIE': None,
}
Front-end code when action triggers.
export const updateAppTypeData = (appData) => async dispatch => {
const token = localStorage.getItem('token')
console.log(token)
const headers = {
"Content-Type": "application/json",
"Authorization": "JWT "+ token,
}
const data = {"appType":"Kilo"} // Custom send
const response = await axios.put('http://localhost:8000/api/posts/appType/1/',JSON.stringify(data),headers)
//dispatch({ type : FETCH_APP_TYPE , payload: response.data });
};
Error :
Upvotes: 0
Views: 937
Reputation: 4176
This setup works for me,
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
and View
with authentication_classes
, authentication_classes should be tupple, so if you use one authentication class make sure to use "," at the end authentication_classes = (TokenAuthentication,)
class MainPollVoteByUser(viewsets.ViewSet):
serializer_class = MainPollVoteSerializer
permission_classes = [IsOwnerOrReadOnly, IsAuthenticated]
authentication_classes = (TokenAuthentication,SessionAuthentication)
Upvotes: 0
Reputation: 3674
I think you are using the axios.put method wrong.
You need to pass the config containing a key named headers
in it. You are currently passing headers directly as the third argument.
Solution:
axios.put(
'http://localhost:8000/api/posts/appType/1/',
JSON.stringify(data),
{
headers: headers
}
)
Upvotes: 1