Roger
Roger

Reputation: 5071

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

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

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

Upvotes: 10

Views: 5605

Answers (2)

Mario Orlandi
Mario Orlandi

Reputation: 5849

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

  • optionally since Django 1.1
  • required since Django 2.1

See:

Upvotes: 0

Will Hardy
Will Hardy

Reputation: 14836

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.

Upvotes: 11

Related Questions