Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django OAuth Toolkit giving me "Authentication credentials were not provided" error

Tags:

python

django

I've been trying for a while to get django Oauth toolkit to work but no matter what I get a 401 error and when I check the details it's the error in the title. Even though I'm obviously passing credentials

views.py:

class PostCarFax(viewsets.ModelViewSet):

    #authentication_classes = [authentication.TokenAuthentication, authentication.SessionAuthentication, authentication.BaseAuthentication]
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    queryset = CarFax.objects.all()
    serializer_class = CarFaxSerializer

serializers.py:

class CarFaxSerializer(serializers.ModelSerializer):

    class Meta:
        model = CarFax
        fields = ('vin', 'structural_damage', 'total_loss',
                  'accident', 'airbags', 'odometer', 'recalls',
                  'last_updated', 'origin_country')

    def create(self, validated_data):
        return CarFax.objects.create(**validated_data)

settings.py

import os
import django_heroku
from django.conf import settings
settings.configure()

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ts_0a3(d9$$g4h&_w#k$op7a)lg3@vrk!^fs!m-zv=))rw$=xi'

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

ALLOWED_HOSTS = []

'''import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", __file__)
import django
django.setup()'''




# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'api',
    'oauth2_provider',
    'rest_framework',
    'rest_framework.authtoken',
]

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',
    'oauth2_provider.middleware.OAuth2TokenMiddleware',
]

ROOT_URLCONF = 'django_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',
            ],
        },
    },
]

OAUTH2_PROVIDER = {
    # this is the list of available scopes
    'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}
}

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAdminUser',
    ],
}

AUTHENTICATION_BACKENDS = (
    'oauth2_provider.backends.OAuth2Backend',
    # Uncomment following if you want to access the admin
    #'django.contrib.auth.backends.ModelBackend'
)

calls.py:

def api_call(test):

    headers = {
        "Content-Type": "application/json",
        'Authorization': 'Bearer *********************',
    }


    data = {
        "vin": test[0],
        "structural_damage": test[2],
        "total_loss": test[1],
        "accident": test[5],
        "airbags": 'TESTTTTT',
        "odometer": test[4],
        "recalls": test[6]
    }

    data = json.dumps(data)
    response = requests.post('http://127.0.0.1:8000/api/v1/post_carfax/', headers=headers, data=data)
    # print(json.dumps(response.json))
    return response.text

I've tried playing around with the settings a lot, I am not sure what I should do. The credentials are being passes right there in the headers, I am not sure why it's saying they don't exist

Fixed it for anyone in the future

I just need to use path() like the tutorial used instead of url(). I didn't use it because on IntelliJ it was underlined and gave me an unresolved error

like image 238
Amon Avatar asked Dec 03 '18 21:12

Amon


1 Answers

Add the following code to your settings.py file:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    )
}
like image 121
Tarjeet Singh Avatar answered Sep 19 '22 03:09

Tarjeet Singh