Search code examples
pythondjangodjango-rest-frameworkdjango-oauth

Getting Permissions issue on sending the authenticated request to OAuth2.0 Django rest Framwork


I Have integrated the OAuth2.0 with django-rest-framework. When I send the authenticated request to my class based view I got this

{
    "detail": "You do not have permission to perform this action."
}

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 import permissions
    from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
    class LogoutView(APIView):
        """
            This will help in logout of user.
        """
        authentication_classes = ()
        permission_classes = (permissions.IsAuthenticated, TokenHasReadWriteScope)

        def get(self, request):
            return Response({'s': 'd'})

urls.py

from django.urls import path, re_path
from accounts.views import SignUpView, LoginView, LogoutView

urlpatterns = [
    path('signup/', SignUpView.as_view()),
    path('login/', LoginView.as_view()),
    path('logout/', LogoutView.as_view()),
]

And this is what my headers look like

Content-Type:application/json
Authorization:Bearer 4A7qGgmHpbEWlJn5w4wCwxJ9jWfTZ5

This is the access token that I generated.


Solution

  • Make sure you have the following in your settings.py

    AUTHENTICATION_BACKENDS = (
        'oauth2_provider.backends.OAuth2Backend',
        'django.contrib.auth.backends.ModelBackend'
    )
    

    And:

    OAUTH2_PROVIDER = {
        'REFRESH_TOKEN_EXPIRE_SECONDS': 360000,
        'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'},
        'ACCESS_TOKEN_EXPIRE_SECONDS': 1800
    }
    

    For debugging purposes:

    • Remove authentication_classes = () from view.py
    • Remove TokenHasReadWriteScope from view.py

    If you want to make a logout endpoint, I would recommend using oauth2_views in your urls.py:

    from oauth2_provider import views as oauth2_views
    #.....
    
    urlpatterns = [
        #....
        url(r'^logout/$', oauth2_views.RevokeTokenView.as_view()),
    ]