Django-rest-framework with django OAuth 2.0 giving

2019-07-13 03:09发布

问题:

I have integrated django-rest-framework with django-oauth-toolkit. And it is giving me {"detail": "Authentication credentials were not provided."} with un authenticated apis.

Here's my settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

views.py

from rest_framework.views import APIView
from rest_framework.response import Response


class SignUpView(APIView):
    """
        Signup for the user.
    """
    def get(self, request):
        return Response({'result': True, 'message': 'User registered successfully.'})

urls.py

from django.urls import path
from myapp.views import SignUpView

urlpatterns = [
    path('signup/', SignUpView.as_view()),

]

回答1:

For registering a user, you do not need any authentication. So you need to write your view like this.

class SignUpView(APIView):
    """
        Signup for the user.
    """
    authentication_classes = ()
    permission_classes = ()

    def get(self, request):
        return Response({'result': True, 'message': 'User registered successfully.'})

For all other requests, you need to pass auth token in your header. In that case, you will not have any need to mention authentication and permission classes as your default classes will be used.