Reputation: 9790
I've been trying to fix this for a few hours now, please help me if you can.
When I try to make get
requests w/ axios in my React app to my DRF Rest API it returns 403.
App.js:
axios
.get(API_POSTS, {
headers: {
Authorization: `Token 27dbb4dd8299792c8c52022f829da4ecec22f437`
}
})
.then(res => {
console.log("Success");
})
.catch(error => {
console.log(error);
});
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
# 3rd-party apps
'rest_framework',
'rest_framework.authtoken',
'allauth',
'allauth.account',
'allauth.socialaccount',
'rest_auth',
'rest_auth.registration',
'corsheaders',
# Local
'posts.apps.PostsConfig',
'users.apps.UsersConfig',
]
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000',
]
# Rest Framework
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
],
}
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
SITE_ID = 1
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER': 'users.serializers.CustomRegisterSerializer',
}
I have a posts
endpoint that only authenticated users can see.
After logging in from within my React APP this token was generated. (using plain text for now because I'm testing)
So, when I try to make a get request with it, it returns the following error:
Error: Request failed with status code 403
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:60)
Why is this happening? Do I need to send any more information via the Header? I have read other questions and the documentation but can't find an answer.
Thank you.
Upvotes: 2
Views: 1572
Reputation: 9790
Ok, I managed to find out what was wrong. I had to allow TokenAuthentication
in my app.
So what I did was:
settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
views.py
class PostList(generics.ListCreateAPIView):
authentication_classes = (TokenAuthentication, )
queryset = Post.objects.all()
serializer_class = PostSerializer
After that it worked just fine.
Hope it helps everybody.
Upvotes: 7