如何在Django自定义身份验证后端中访问请求? [英] how to access the request in a django custom authentication backend?

查看:45
本文介绍了如何在Django自定义身份验证后端中访问请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对Django的身份验证执行以下操作:

I want to do the following with django's authentication:

  • 记录错误的登录尝试
  • "x"次不正确的登录尝试后暂时锁定帐户
  • 登录成功登录.

我认为自定义身份验证后端将是解决方案.

I thought a custom auth backend would be the solution.

我可以做我想做的大部分事情,但是我想记录尝试用户的IP和REMOTE_HOST.

I can do most of what i want, but I want to log the IP and REMOTE_HOST of the user making the attempt.

如何访问auth后端中的请求对象?

how can I access the request object in the auth backend?

谢谢

推荐答案

身份验证后端可以为 authenticate()方法采用任意数量的自定义参数.例如:

The authentication backend can take any number of custom parameters for the authenticate() method. For example:

class MyBackend:
    def authenticate(self, username=None, password=None, request=None):
         # check username, password
         if request is not None:
             # log values from request object

如果要在自己的视图中调用身份验证,则可以传递请求对象:

If you are calling authenticate in your own view, you can pass the request object:

from django.contrib.auth import authenticate

def login(request):
    # discover username and password
    authenticate(username=username, password=password, request=request)
    # continue as normal

如果您使用的是django的登录视图(或管理员登录),则不会获得额外的信息.简而言之,您将必须使用自己的自定义登录视图.

If you're using django's login view (or the admin login), you wont have the extra information. Put simply, you'll have to use your own custom login view.

此外,在自动锁定帐户时要小心:您允许某人故意锁定用户的帐户之一(拒绝服务).有一些解决方法.另外,请确保您的错误尝试日志中没有任何尝试输入的密码.

Also, be careful when automatically locking accounts: you allow someone to deliberately lock one of your user's accounts (denial of service). There are ways around this. Also, make sure your log of incorrect attempts doesn't contain any attempted passwords.

这篇关于如何在Django自定义身份验证后端中访问请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆