4
votes

I'm creating a web services that use JWT Auth. I'm using django-rest-framework-jwt for that. I want my users could authenticate using their ldap accounts. I have found that there's a Django authentication backend that authenticates against an LDAP service. The function that does the authentication in django-rest-framework-jwt is coded like this :

def authenticate_credentials(self, payload):
    try:
        user_id = payload.get('user_id')

        if user_id:
            user = User.objects.get(pk=user_id, is_active=True)
        else:
            msg = 'Invalid payload'
            raise exceptions.AuthenticationFailed(msg)
    except User.DoesNotExist:
        msg = 'Invalid signature'
        raise exceptions.AuthenticationFailed(msg)

    return user   

The function looks in the User model to authenticate the user. I think that even if I setup the ldap backend, it will never work. Am I right? If yes what can I change to be able to use JWT Auth and be able to authenticate against LDAP service?

1
Hunsu, were you able to integrate JWT auth and LDAP as suggested by psagers. I'm in the same situation and will try that.ankit tyagi
@ankittyagi it was a while ago and I don't really remember but as I accepted the answer I think I did (or at least it did help me).Hunsu

1 Answers

6
votes

Every Django authentication backend has a very simple API. Normally, they're installed in the AUTHENTICATION_BACKENDS setting, but there's nothing stopping you from using them manually:

from django_auth_ldap.backend import LDAPBackend

user = LDAPBackend().authenticate(username, password)

This is assuming that users are authenticating with a username and password. If you need to authenticate against LDAP by some other means, then you're probably on your own.

One thing to keep in mind is that every authentication backend will create/return the same User model objects. So assuming a user has been authenticated once, your user_id-based code above should be compatible with any underlying backend.