Django 403 "detail": "Authentication credentials were not provided." Knox Tokens

20 Views Asked by At

I was following this tutorial (https://github.com/bradtraversy/lead_manager_react_django/tree/db45e4f6fc05a3481e7b8a0223e0aab0355a84b6) to make a Django-React-Redux application. I am having trouble with my UserAPI, specifically when making a GET request. Note that I am using knox tokens. As the logout function works fine (this function is a default from knox), I can see that the token is properly generated from the login, as I use this token for logout. I suspect that there is something in my settings.py that is wrong.

The error is: 403: "detail": "Authentication credentials were not provided."

class UserAPI(generics.RetrieveAPIView):
    # this route needs protection
    # need a valid token to view
    permission_classes = [
        permissions.IsAuthenticated,
    ]
    serializer_class = UserSerializer

    def get_object(self):
        return self.request.user

    # Get the registered organizations of the user
    @action(methods=['get'],detail=True)
    def registered_orgs(self,request,*args,**kwargs):
        instance = self.get_object()

        orgs = instance.followed_organizations.all()

        serializer = OrganizationSerializer(orgs,many=True)

        return Response(serializer.data)

Here is my settings file:

"""
Generated by 'django-admin startproject' using Django 4.1.1.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path

import os

import mimetypes
mimetypes.add_type("text/javascript", ".js", True)

# 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/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-8-#*v%6fb-w7qt0%b91po)zp^qbqz$ub%&^3k$ian+&@714lz-'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1','localhost','*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "whitenoise.runserver_nostatic",

    # rest framework
    'rest_framework',
    'rest_framework.authtoken',

    # data
    'data.apps.DataConfig',

    # accounts
    'accounts.apps.AccountsConfig',

    # frontend
    'frontend.apps.FrontendConfig',

    # organization
    'organizations.apps.OrganizationsConfig',

    # social aspect
    'social.apps.SocialConfig',

    # for token authenitcation
    'knox',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES':('knox.auth.TokenAuthentication',)
}

MIDDLEWARE = [
    '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',
    "whitenoise.middleware.WhiteNoiseMiddleware",
]

ROOT_URLCONF = 'delta.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 = 'delta.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.1/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/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]
STATIC_ROOT = os.path.join(BASE_DIR,'delta','static')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_URL = '/static/'

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR,'delta','media')

# Attempted solution to loading image issue
MEDIA_ROOT = Path.joinpath(BASE_DIR, 'media')
MEDIA_URL = '/media/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.MultiPartParser',
        # other parsers...
    ],
}

CSRF_COOKIE_NAME = "XSRF-TOKEN"

User serializer file:

# User serializer
class UserSerializer(serializers.ModelSerializer):
    # Number of followed organizations
    followed_organization_count = serializers.SerializerMethodField()
    # The followed organizations
    followed_organizations = serializers.SerializerMethodField()
    # bio
    bio = serializers.SerializerMethodField()

    class Meta:
        # Need unique validator on name and email https://stackoverflow.com/a/38160343/12939325
        model = User
        fields = ('id','username','email','first_name','last_name',
            'followed_organization_count','followed_organizations','bio')
        # cant change id
        read_only_fields = ['id']
    
    def get_followed_organization_count(self,obj):
        return len(obj.followed_organizations.all())
    
    def get_followed_organizations(self,obj):
        listOrgs = obj.followed_organizations.all()
        serializer = OrganizationSerializer(listOrgs,many=True)
        return serializer.data
    
    def get_bio(self,obj):
        return obj.profile.bio

I can make a login request using Postman, get the token from knox, and then use it for the logout. However, I cannot call any custom made functions that require some permissions class.

I have looked online for a solution, but have found none.

Here's my Postman request: Postman request

Please let me know if there is anything else I can provide to help solve this. Thanks!

0

There are 0 best solutions below