简体   繁体   中英

Django: Authentication credentials were not provided

I've pulled up a dozen similar SO posts on this topic, and have implemented their solutions to the best that I have understood them, yet they haven't worked for me. Why am I getting this error detail: "Authentication credentials were not provided." after using an AJAX Patch request to hit my Django Rest Framework endpoint? I appreciate your help!

Some Details

  • The header tells me "Status Code: 401 Unauthorized"
  • I'm on my localHost development server (Postgres)
  • I don't get this error with any other django forms or ajax (Get and Posts) requests running on other apps within this application.
  • This is the first time I'm attempting a PATCH request
  • Ultimately, Once this Ajax Patch request works I, simply want to add bookid to the ManyToManyField books field in the api.BookGroup model
  • I've tried to follow the suggestions in similar posts which recommend adjusting the settings.py to allow the right authentication and permission methods.
  • referring to the DRF documentation , I've also changed the permission classes to permission_classes = (IsAuthenticated,) which should allow a patch request if I'm logged in when making the request (and yes, I am definitely logged in)
  • The form data in the ajax header shows that I am correctly passing the CSRF token and the proper variables:

     csrfmiddlewaretoken: UjGnVfQTfcmkZKtWjI0m89zlAJqR0wMmUVdh1T1JaiCdyRe2TiW3LPWt bookid: 1 bookgroupid: 71 

AJAX

function AddToBookGroup(bookgroupid,bookid){
 $.ajax({
    type: "PATCH",
    url: '/api/bookgroups/'+bookgroupid+'/',
    data: {
        csrfmiddlewaretoken: window.CSRF_TOKEN,
        bookid: bookid,
        bookgroupid: bookgroupid
        }, 
    success: function(data){
        console.log( 'success, server says '+data);  
    }
 });
}

URLS.py

from django.urls import path, include
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', include(router.urls)),
    url(r'bookgroups/\d+/$', views.BookGroupUpdateSet.as_view()),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

VIEWS.py

from rest_framework.generics import ListAPIView, DestroyAPIView, UpdateAPIView, RetrieveAPIView
from rest_framework.authentication import TokenAuthentication, SessionAuthentication, BasicAuthentication
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from . import serializers, models, permissions

class BookGroupUpdateSet(UpdateAPIView):
    queryset = models.BookGroup.objects.all()
    model = models.BookGroup
    serializer_class = serializers.BookGroupUpdateSerializer

    def patch(self, request, pk=None):
        permission_classes = (IsAuthenticated,)
        authentication_classes = (TokenAuthentication,)
        bookid = request.Patch['bookid']
        bookgroupid = request.Patch['bookgroupid']
        print("...Print stuff...")

SETTINGS.py

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

AUTH_USER_MODEL = "api.UserProfile"

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
   'rest_framework.authentication.TokenAuthentication',
   'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
    # 'rest_framework.permissions.AllowAny',  # I've tried this too, same results
    'rest_framework.permissions.IsAuthenticated',
)
}

Once your API View requires authentication for being accessed, you need to provide to the request's header the Authorization header: Authorization: Token <token>

So, how do you get this Token? According to the DRF documentation, You need to create a token for each user in your database. So, you have to do manually whenever a new user is created or you can use the DRF Token authentication views by importing and using:

from rest_framework.authtoken.views import ObtainAuthToken

But I suggest You use the django-rest-auth app, It makes easier the Token authentication process in DRF. https://django-rest-auth.readthedocs.io/en/latest/

With Django Rest Framework views, you don't use CSRF Tokens, but custom DRF tokens instead (that is what rest_framework.authtoken is for). When you create a new user, you have to create his token, like this:

def create(self, validated_data):
    from rest_framework.authtoken.models import Token

    try:
        user = models.User.objects.get(email=validated_data.get('email'))
    except User.DoesNotExist:
        user = models.User.objects.create(**validated_data)

        user.set_password(user.password)
        user.save()
        Token.objects.create(user=user) # -------> Token creation

        return user
    else:
        raise CustomValidation('eMail already in use', 'email', status_code=status.HTTP_409_CONFLICT)

Then, you have to get the token for the user, and send it in the header with key name Authorization and value Token <token> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM