I’m trying to restrict access to some views of my API using Django Rest Framework and simpleJWT https://django-rest-framework-simplejwt.readthedocs.io/
The issue I’m facing is that postman correctly block with
{
"detail": "Authentication credentials were not provided."
}
access to my views when I do not provide a valid JWT to my API but my Angular front-end does not and gives access to all the views of my DRF API.
Here is a view
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication
from ..serializer import General_emission_group_serializer_years
from django.db import connection
class EmmissionGroup(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
Here is my settings.py
from pathlib import Path
import os
import environ
from django.contrib.auth import get_user_model
from django.contrib.staticfiles import handlers
class CORSStaticFilesHandler(handlers.StaticFilesHandler):
def serve(self, request):
response = super().serve(request)
response['Access-Control-Allow-Origin'] = '*'
return response
handlers.StaticFilesHandler = CORSStaticFilesHandler
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
env = environ.Env()
environ.Env.read_env(os.path.join(BASE_DIR, ".env"))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["127.0.0.1"]
DATABASES ={'default':
{
'ENGINE': env.str('DB_ENGINE'),
'NAME':env.str('DB_NAME'),
'USER':env.str('DB_USER'),
'PASSWORD':env.str('DB_PASSWORD'),
'HOST':env.str('DB_HOST'),
'PORT':env.int('DB_PORT')
}
}
# Application definition
INSTALLED_APPS = [
"corsheaders",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework_simplejwt',
#"rest_framework.authtoken",
"django_filters",
"camping",
"admin_honeypot",
"axes",
]
AUTHENTICATION_BACKENDS = [
'rest_framework.authentication.TokenAuthentication', # Token-based authentication for API
'django.contrib.auth.backends.ModelBackend', # Default Django authentication backend
'axes.backends.AxesStandaloneBackend',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'axes.middleware.AxesMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
AXES_ENABLED = True
AXES_COOLOE_NAME = 'axes'
ROOT_URLCONF = 'WebCamping.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 = 'WebCamping.wsgi.application'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
# AUTH_USER_MODEL = 'camping.Login'
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',
},
]
#CORS
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
"http://localhost:4200",
]
CORS_ALLOW_METHODS = [
'GET',
'OPTIONS',
'POST',
'PUT',
'DELETE',
]
# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
"C:/Projets/Stage/Camping/WebCamping/camping/static",
]
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
And my urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
from camping.views.camping_view import CampingViewSet
from camping.views.client_view import ClientViewSet
from camping.views.adresse_view import AdresseViewSet
from rest_framework.routers import DefaultRouter
from camping.views.gen_dashboard_emissions_group_view import EmmissionGroup
from camping.views.pie_chart import Pie_chart
from camping.views.distance_by_mean_of_transport_view import Distance_by_mean_of_transport
from camping.views.emission_by_mean_of_transport_view import Emissions_by_mean_of_transport
from camping.views.insert_new_value import Insert_value
from camping.views.login_view import LoginView
router = DefaultRouter()
router.register(r'client', ClientViewSet)
router.register(r'camping', CampingViewSet)
router.register(r'adresse', AdresseViewSet)
urlpatterns = [
path('secretadmin/',admin.site.urls),
path('admin/', include("admin_honeypot.urls")),
path('gen_em_group/', EmmissionGroup.as_view(), name="Emmission_group_per_year"),
path('pie_chart/', Pie_chart.as_view(), name="Pie_chart"),
path('distances_by_mean_of_transport/', Distance_by_mean_of_transport.as_view(), name="Distance_by_mean_of_transport"),
path('emissions_by_mean_of_transport/', Emissions_by_mean_of_transport.as_view(), name="Emission_by_mean_of_transport"),
path('insert_value/', Insert_value.as_view(), name = "Insert_value"),
path('login/', LoginView.as_view(), name='Login'),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('', include(router.urls))
]