Get username for authenticated user for Basic Auth

I am trying to store the username that the authenticated user input when logging into Dash as a variable. How do I do this?

I have read through the following thread, but still have not been able to figure it out:

Any help would be greatly appreciated! Thanks!

1 Like

Are you already using any type of authentication?

There are two methods of authentication described in the Dash docs and you can find it here: https://dash.plot.ly/authentication.

You can also use Flask-Login to do this: https://flask-login.readthedocs.io/en/latest. With this method you can manage the users in a simple SQLite database and retrieve the user name once logged-in. I am using this method in an application I am building and it works really well with Dash.

hi @RafaelMiquelino, thanks for your response!

I am currently using the Basic Auth provided by Dash. I’m trying to retrieve the username so I can map the username to unique ‘property’ and ‘region’ strings. I will then use these ‘property’ and ‘region’ strings as filters within WHERE statements within my query. I have the Dash app currently connected to BigQuery.

Thanks for suggesting the Flask-Login; I’ll take a look at that method.

Can you share the code as example,thank you

hi @RafaelMiquelino,

Thanks for your suggestion again. I was able to set up the Flask login and connect it to my dash app. How were you able to use the retrieved username outside of the flask route definition and within the dash layout?

Thanks!

Hello @swwong, you should be able to do this with the following code:

#Init user session
from flask_login import current_user

@app.callback(
    Output('user-div', 'children'),
    [Input('user-div', 'id')])
def cur_user(input1):
    if current_user.is_authenticated:
        return 'Current user: '+current_user.username
    else:
        return 'User non authenticated' # or 'some fake value', whatever

This way you’ll have the username available in the ‘children’ property of the ‘user-div’ object (html.Div).

Hope it helps.

1 Like

Did it work @swwong?

hi @RafaelMiquelino
yes, it did! thanks for your help!

Hello, for whom it may be useful, I made available a simple example of the Flask-login implementation on top of a dash app here: https://github.com/RafaelMiquelino/dash-flask-login.

3 Likes