Black Lives Matter. Please consider donating to Black Girls Code today.
Dash Enterprise delivers an incredible 21x cost savings 💸Download the e-book!

What is the correct way to integrate LDAP authentication with Dash-Auth?

Hi everyone.

I went to basic_auth.py file in Dash-Auth and changed the is_authorized function to return True or False based on a LDAP authentication function.

def is_authorized(self):

    header = flask.request.headers.get('Authorization', None)
    if not header:
        return False

    username_password = base64.b64decode(header.split('Basic ')[1])
    username_password_utf8 = username_password.decode('utf-8')
    username, password = username_password_utf8.split(':')

    return ldap_auth(username, password)

It actually works fine, but the problem is that it runs this method and reconnects to the LDAP server every time a component updates, making the app slower.

Is this BasicAuth behavior intended?
Is there a way to have it verify/authenticate only when the user opens a session?
Should I use something like Flask-Login instead?

Sorry if these are silly questions. I’m very new in LDAP/Auth stuff, so I’m not even sure I’m using the correct terms to describe the problem.

Thanks in advance.

I use flask-session to store a server-side session expiration (datetime) and then compare the expiration with the current time for every request. This way, you only have to authorize one time. You could also set a browser cookie with an expiration, which would get checked with every request.

Thank you very much.
I did a couple of tests using this idea, and it looks like it works.

Hello @GusFurtado,

do you have any example code how you fixed it ?

Using LDAP request for every new updateis a bit too much indeed…

KR!

or @cufflink do you have some guidance to your solution ?

I have used Keycloak with success. It has a lot of advantages in terms of flexibility, but it requires running a separate Keycloak server. If you don’t want that, i would go with @cufflink’s suggestion :slight_smile:

I use Redis to store a server-side session via flask-session and flask-redis. Here is a link to both, which have some usage examples.

There’s quite bit to chew on there, so let me know if you run into anything specific that you need guidance on.

1 Like

I tried keep things simple and did something like this:

import flask
import ldap3

def check_ldap(user, password):
    ldap_server = ldap3.Server('<your_server>', get_info=ldap3.NONE)
    try:
        ldap3.Connection(
            ldap_server,
            user = f"<your_domain>\\{user}",
            password = password,
            authentication = ldap3.NTLM,
            auto_bind = True
        )
        flask.session['authenticated'] = True
    return

if 'authenticated' in flask.session:
    <continue_to_app>
else:
    <go_to_login_screen>
1 Like

Okay thanks to both of you !! It worked like a charm !