how to access the request in a django custom authentication backend?

跟風遠走 提交于 2021-02-06 21:57:07

问题


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

  • Log incorrect log-in attempts
  • Temporarily lock accounts after 'x' number of incorrect log-in attempts
  • Log successful log-ins.

I thought a custom auth backend would be the solution.

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

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

Thanks


回答1:


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

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.




回答2:


In recent versions of Django, authenticate() accepts "request" as first parameter:

  • optionally since Django 1.1
  • required since Django 2.1

See:

  • https://docs.djangoproject.com/en/2.1/releases/1.11/#deprecated-features-1-11
  • https://docs.djangoproject.com/en/2.1/releases/2.1/


来源:https://stackoverflow.com/questions/3488307/how-to-access-the-request-in-a-django-custom-authentication-backend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!