Reputation: 655
In my project, I have Django Rest Framework managing the backend and React on the frontend.
I am currently implementing the authentication system, so I have just switched the REST_FRAMEWORK
settings for the DEFAULT_PERMISSION_CLASSES
from rest_framework.permissions.AllowAny
to rest_framework.authtoken
(before everything worked just fine).
Just to make things clearer, here is my settings.py
(from INSTALLED_APPS
):
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Custom Apps
'rest_framework',
'assessments',
'corsheaders',
'accounts',
'rest_framework.authtoken',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'rest_auth.registration',
'allauth.socialaccount' # needed for delete user
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'api.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'api.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
# 'rest_framework.permissions.AllowAny'
'rest_framework.authtoken'
]
}
CORS_ORIGIN_ALLOW_ALL = True
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER': 'accounts.serializers.RegisterProfileSerializer',
}
REST_AUTH_SERIALIZERS = {
'USER_DETAILS_SERIALIZER': 'accounts.serializers.UserProfileSerializer'
}
SITE_ID = 2
Also, tho make things as 'restful' as possible, I have used django-rest-auth
in order to have endpoints form my authentication system.
So far I have managed to implement API endpoints for rest-auth/registration/
and rest-auth/users
.
Again, from the API point of view, everything works. In fact, I am able to register a user with an extra field and to see the user details correctly.
My problem is that when I try to make a GET
request via the fetch
function in React, I receive back a GET http://127.0.0.1:8000/rest-auth/user/ 403 (Forbidden)
.
I thought this is due to the tokens, so after a little search I have found out this way to make the fetch request:
async getUserRole() {
await fetch("http://127.0.0.1:8000/rest-auth/user/",
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': ' Token e68edf2d326bef3b12b3008c851261b0c7c3dced',
}
}
)
.then(response => response.json())
.then(data => this.setState({ userRole: data.role }))
}
As you can see I am specifying the actual token for the current user, as shown in the admin page:
(I know that from this picture you might be thinking I am trying to make the GET
request when logged in as the admin, and therefore the token is not right, but I am actually logging out and then back in as the user mirko
from the Django Rest Framework API.)
So, is there anybody that knows what I am doing wrong here?
Upvotes: 1
Views: 2236
Reputation: 21
Logout from Django Admin, or try to login with different user than Django Admin.
Upvotes: 0
Reputation: 2402
I used a google chrome "API Tester" to test my api, the issue was that my admin portal was logged in with the same user and it was preventing me from sending a post request. I had the authentication classes session and token.
Upvotes: 2
Reputation: 655
The problem is was that I have to add
DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
To the REST_FRAMEWORK
settings, as specified here
Upvotes: 3