请求对象在DRF + DOT中没有属性“ oauth2_error”

时间:2019-06-15 20:41:50

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

我正在使用djangorestframework和django-oauth-toolkit作为我的API。

我有一个相当简单的用户注销视图,它支持带令牌吊销的DOT注销和常规Django会话注销:

class UserLogoutView(APIView):
    permission_classes = (IsAuthenticated,)

    @staticmethod
    def post(request):
        logout(request)

        if request.auth is None:
            return Response('OK')

        app = request.auth.application
        client_id = app.client_id
        client_secret = app.client_secret
        token = request.auth.token

        r = requests.post(settings.OAUTH_URL.format('revoke-token'), data={
            'client_id': client_id,
            'client_secret': client_secret,
            'token': token,
        })

        if r.status_code != 200:
            raise AuthenticationFailed('Failed to revoke token')

        return Response('OK')

如果令牌吊销出了点问题,我希望得到一个带有错误的401响应,但是相反,我在服务器端却收到了一个错误(这是由于将AuthenticationFailed的状态提高为回溯状态):

AttributeError: 'Request' object has no attribute 'oauth2_error'

我想DRF + DOT组合的异常处理有问题,但是如何解决?

UPD :我的settings.py中与DRF,身份验证或DOT相关的所有内容:

INSTALLED_APPS = [
    ...
    'rest_framework',
    'oauth2_provider',
    ...
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

AUTHENTICATION_BACKENDS = [
    'oauth2_provider.backends.OAuth2Backend',
    'django.contrib.auth.backends.ModelBackend',
    'guardian.backends.ObjectPermissionBackend',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
}

UPD 2:我尝试从SessionAuthentication中删除DEFAULT_AUTHENTICATION_CLASSES并根据模块文档设置应用顺序(在rest_framework之后写oauth2_provider) ,一切都没有运气。

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,并找到了解决方案:django-oauth-tookit 1.2.0中存在一个错误(请参见https://github.com/jazzband/django-oauth-toolkit/pull/716),该错误已在master分支中修复。不幸的是,没有新版本,所以我不得不继承OAuth2Authentication并提供缺少的属性:

 def authenticate_header(self, request):
     request.oauth2_error = {}
     return super().authenticate_header(request)