获取权限问题将经过身份验证的请求发送到OAuth2.0 Django休息Framwork

时间:2018-02-15 11:59:50

标签: python django django-rest-framework django-oauth

我已将OAuth2.0与django-rest-framework集成在一起。当我将经过身份验证的请求发送到基于类的视图时,我得到了这个

{
    "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()),
]

这就是我的标题看起来像

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

这是我生成的访问令牌。

1 个答案:

答案 0 :(得分:7)

确保settings.py

中包含以下内容
AUTHENTICATION_BACKENDS = (
    'oauth2_provider.backends.OAuth2Backend',
    'django.contrib.auth.backends.ModelBackend'
)

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

出于调试目的:

  • 从view.py
  • 中删除authentication_classes = ()
  • 从view.py
  • 中删除TokenHasReadWriteScope

如果您想制作退出端点,我建议您在urls.py中使用oauth2_views

from oauth2_provider import views as oauth2_views
#.....

urlpatterns = [
    #....
    url(r'^logout/$', oauth2_views.RevokeTokenView.as_view()),
]