微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将django-axes与自定义的django rest框架和simpleJWT

如何解决将django-axes与自定义的django rest框架和simpleJWT

我是Django的初学者,正在构建一个登录系统。我想将轴与django rest框架和simpleJWT结合使用。 根据Django-Axes的文档:

3.7.0之后的Django REST Framework的现代版本可以直接使用Axes,并且不需要在DRF中自定义

现在,我为我的项目构建了一个自定义用户,该用户使用自己的自定义身份验证后端进行了身份验证。为了创建 Access Refresh 令牌,我有一个localhost:8000/api/login端点,该端点创建了这两个令牌并将它们存储为HTTPOnly cookie。 登录视图如下:

@api_view(['POST'])
@permission_classes([AllowAny])
@ensure_csrf_cookie
def login_view(request):

    # print("captcha token = ",request.POST.get('g-recaptcha-response'))

    Account = get_user_model()
    EmailId = request.data.get('EmailId')
    password = request.data.get('password')
    response = Response()
    if (EmailId is None) or (password is None):
        raise exceptions.AuthenticationFailed('username and password required')

    # get the user with the credentials provided
    user = Account.objects.filter(EmailId=EmailId).first()

    if not check_user_validity(user,password):
        # locking the user
        raise exceptions.AuthenticationFailed('The credentials are invalid')
    else:
        print('user is valid')

    # get the token values
    tokenvals = get_jwt_tokens(user)

    response.set_cookie(key='refreshtoken',value=tokenvals['refresh_token'],httponly=True)
    response.set_cookie(key="accesstoken",value=tokenvals['access_token'])
    response.data = {
        'access_token': tokenvals['access_token'],'id': user.id
    }

    return response

我可以使用localhost:8000/api/Refresh端点刷新访问令牌。

  • get_jwt_token(user)返回一个字典,其中包含以自定义方式创建的访问和刷新令牌。它不使用任何JWT序列化程序或视图。

对于登录视图,我想使用轴在多次无效登录后阻止用户。但是我不知道如何从这里开始。

我遵循了轴的文档,并像提到的那样修改了设置文件

AUTHENTICATION_BACKENDS = [
    # AxesBackend should be the first backend in the AUTHENTICATION_BACKENDS list.
    'axes.backends.AxesBackend',# Django ModelBackend is the default authentication backend.
    'django.contrib.auth.backends.ModelBackend',]

MIDDLEWARE = [
    ..
    ..
    ..
# at the end 
'axes.middleware.AxesMiddleware',]

INSTALLED_APPS = [
    ..
    ..
    ..
   "authentication","axes",]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        # a custom authentication method
        'authentication.authentication.SafeJWTAuthentication',],'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',# make all endpoints private
    )
}

从现在开始我该如何进行?自从我做了大量的自定义操作以来,我真的想不起来。

  • 由于使用自定义身份验证,我还应该在后端包括'django.contrib.auth.backends.ModelBackend',吗?

从现在开始我该如何进行?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。