django-axes没有获取请求参数

时间:2019-09-26 18:44:33

标签: django django-rest-framework django-rest-framework-simplejwt

我最近将django-axes添加到了我的Django项目中。假定用django-restframework来确定框。但是,我正在使用django-rest-framework-simplejwt来处理身份验证。但是它仍然可以解决问题,因为django-axes唯一需要做的就是将Django的身份验证方法传递给源代码(line 39 and 43)中的请求对象。

当我尝试进行身份验证时,我从django-axes收到此错误:

  

axes.exceptions.AxesBackendRequestParameterRequired:AxesBackend需要一个请求作为验证的参数

2 个答案:

答案 0 :(得分:0)

您需要向身份验证功能添加请求。请参见下面的示例代码。

serializers.py

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):

    @classmethod
    def get_token(cls, user):
        token = super(MyTokenObtainPairSerializer, cls).get_token(user)

        # Add custom claims
        token['user_name'] = f"{user.first_name} {user.last_name}"
        token['user_photo'] = None
        ...

        return token

    def _authenticate_user_email(self, email, password, request):

        # This is key: Pass request to the authenticate function
        self.user = authenticate(email=email, password=password, request=request)
        return self.user

    def validate(self, attrs):

        password = attrs.get('password')
        email = attrs.get('email')
        request = self.context.get('request')   # <<=== Grab request

        self.user = self._authenticate_user_email(email, password, request)

        ...

views.py

from rest_framework_simplejwt.views import TokenObtainPairView
from authy.serializers import MyTokenObtainPairSerializer

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

urls.py

from authy.views import MyTokenObtainPairView

url(r'^/auth/api/token/$', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),

答案 1 :(得分:0)

使用这个:

from axes.backends import AxesBackend


class MyBackend(AxesBackend)
    def authenticate(self, request=None, *args, **kwargs):
        if request:
            return super().authenticate(request, *args, **kwargs)
<块引用>

如果请求未设置,这将跳过 AUTHENTICATION_BACKENDS 中的 AxesBackend,并且会削弱您的安全设置。

来源:https://github.com/jazzband/django-axes/issues/478