【问题标题】:Custom Django Rest Framework authentication validating when 'None' is returned自定义 Django Rest Framework 身份验证验证何时返回“无”
【发布时间】:2020-03-16 20:51:45
【问题描述】:

我正在努力实现 JWT 进行身份验证。当然,这意味着我必须进行一些自定义身份验证。根据docs,“如果未尝试身份验证,则返回None。”因此,我有代码检查授权标头(JWT 所在的位置),如果授权标头不存在,则返回“无”。这意味着没有尝试授权(并且根据文档)我应该返回None。但是,Django 表示用户已获得授权:

Root/身份验证/TokenAuthentication/TokenAuthentication


from rest_framework import status
from django.http import HttpResponse
from rest_framework.authentication import get_authorization_header, BaseAuthentication
from django.contrib.auth.models import User
import jwt, json

class TokenAuthentication(BaseAuthentication):

    def authenticate(self, request):
        auth = get_authorization_header(request).split()

        if not auth:
            return None

登录.py

@api_view(['POST'])
def login_view(request):
    if not request.data:
        return Response({'Error': "Please provide username/password"}, status="400")

    username = request.data['username']
    password = request.data['password']

    try:
        user = User.objects.get(username=username)

        if not user.check_password(password):
            raise User.DoesNotExist

    except User.DoesNotExist: # if user not found or password is wrong
        return Response({'Error': "Invalid username/password"}, status="400")

    if user.is_authenticated:
        print("user is authenticated") # THIS GETS PRINTED
    else:
        print("User is not authenticated")


Settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        #'rest_framework.authentication.BasicAuthentication',
        'Root.authentication.TokenAuthentication.TokenAuthentication'
    ]
}

线

 if user.is_authenticated:
        print("user is authenticated")

每次返回 None 时都会运行。

任何帮助将不胜感激。谢谢。

注意:如果重要的话,我正在使用 PyJwt。

【问题讨论】:

  • 您是否在请求中添加了任何标头?
  • 不,我没有。我是故意这样做的。通过不添加任何标头,该代码将运行并返回 None,但用户仍然经过身份验证。我认为用户不应该这样做。

标签: django authentication django-rest-framework jwt


【解决方案1】:

您正在使用 user.is_authenticated 来检查身份验证,其中 user 是您从数据库中提取的实例

应该是 request.user.is_authenticated

【讨论】: