Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 769
Roger Avatar asked Aug 15 '10 16:08

Roger


People also ask

Which method of authentication backend takes credentials in Django?

An authentication backend is a class that implements two required methods: get_user(user_id) and authenticate(request, **credentials) , as well as a set of optional permission related authorization methods.

How does Django handle user authentication?

The Django authentication system handles both authentication and authorization. Briefly, authentication verifies a user is who they claim to be, and authorization determines what an authenticated user is allowed to do. Here the term authentication is used to refer to both tasks.


1 Answers

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.

like image 58
Will Hardy Avatar answered Oct 05 '22 22:10

Will Hardy