preloader

Add User Authentication to your Dash Application

author image

Introduction

Dash is a great low-code framework for building data apps in Python. It provides simple and efficient tools to rapidly build data-focused web applications and dashboards. One feature it doesn’t provide natively is authentication, which is important if you’ve deployed an application and only want to provide access to specific individuals. In this article, we’ll go over a few methods of adding an authentication layer to your Dash app.

Ploomber Cloud

Adding authentication to your Dash app is very simple with Ploomber Cloud. To start, you need to create an account and follow the instructions to deploy a Dash app.

Create a zip file with the following files:

  • app.py
  • requirements.txt

Now open Ploomber Cloud, create a new application, and add your zip file. Under the deployment options, under Advanced -> Security, click Enable password protection. Then, set any username and password you like, and click Deploy! Be sure to note down the username and password you entered in case you can’t remember it later.

Note: Password protection is currently only available for Pro users, but you can start a 10 day free trial here.

Once your app is deployed, navigate to the page where you’ll need to enter your username and password to access the app. In Chrome, it looks like this:

There you have it! You’ve added authentication to your app in minutes with no extra code needed.

dash-auth

Dash-auth is the standard package for Dash authentication and is developed by the original Dash creators, Plotly. With a few additions to your code, it can provide HTTP Basic Auth to your application.

Start by installing the package:

pip install dash==2.16.1
pip install dash-auth==2.0.0

Now, simply add this snippet to your code for basic authentication:

from dash import Dash
from dash_auth import BasicAuth

app = Dash(__name__)
USER_PWD = {
    "username": "password",
    "user2": "useSomethingMoreSecurePlease",
}
BasicAuth(app, USER_PWD)

This example stores the usernames and passwords in a simple dictionary, which you can imagine wouldn’t be ideal for security. Since you have to manage the passwords yourself, the best option might be storing the hashed passwords in a database and utilizing an authentication function to hash the password and then verify it is present in the database:

from dash import Dash
from dash_auth import BasicAuth

def authorization_function(username, password):
    # Hash the password here
    # and check if it's in the database
    # if so, return True.
    return True


app = Dash(__name__)
BasicAuth(app, auth_func = authorization_function)

That’s a basic walkthrough. The package also provides features like public routes and user groups, feel free to check them out on your own! Here’s a final summary of the pros and cons of dash-auth:

Pros:

  • Simple authentication
  • Specify as many users as you want
  • Easy to install and get running
  • Maintained by the original developers

Cons:

  • Need to add some code and an extra package
  • Users can not log out of applications
  • You are responsible for sending the usernames and passwords to your viewers over a secure channel
  • Your viewers can not create their own account and cannot change their password
  • You are responsible for safely storing the username and password pairs in your code.

dash-enterprise-auth

Dash enterprise auth is an authentication and authorization layer built-in to Plotly’s commercial product, Dash Enterprise. If your company happens to use Dash enterprise, then you can take advantage of its authentication offerings. Per the documentation:

This authentication middleware connects to your organization’s identity provider, allows your end users to log in with SSO, verifies if the user has permission to view the app, and then passes along user information like their username or group.

To use it, make sure you already have an application deployed on Dash Enterprise. Then add dash-enterprise-libraries (Dash Enterprise >= 5.2) or dash-enterprise-auth (Dash Enterprise < 5.2) to your requirements.txt file.

The package provides a few features. It allows you to get information about your app viewer with the get_username and get_user_data methods. You can add a logout button with the create_logout_button method. Here’s an example app using these methods:

from dash import Dash, dcc, html, Input, Output, callback
import dash_enterprise_auth as auth

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = Dash(__name__, external_stylesheets=external_stylesheets)

server = app.server  # Expose the server variable for deployments

# Standard Dash app code below
app.layout = html.Div(className='container', children=[

    html.Div([
        html.H2('Sample App', id='header-title', className='ten columns'),
        html.Div(auth.create_logout_button(), className='two columns', style={'marginTop': 30})
    ]),
    html.Div(id='dummy-input', style={'display': 'none'}),

    html.Div([
        html.Div(
            className='four columns',
            children=[
                dcc.Dropdown(['LA', 'NYC', 'MTL'], 'LA', id='dropdown')
        ]),
        html.Div(
            className='eight columns',
            children=[
                dcc.Graph(id='graph')
            ])
    ])
])

@callback(Output('header-title','children'), Input('dummy-input', 'children'))
def update_title(_):

    # print user data to the logs
    print(auth.get_user_data())

    # update header with username
    return 'Hello {}'.format(auth.get_username())

@callback(Output('graph', 'figure'),
              Input('dropdown', 'value'))
def update_graph(value):
    return {
        'data': [{
            'x': [1, 2, 3, 4, 5, 6],
            'y': [3, 1, 2, 3, 5, 6]
        }],
        'layout': {
            'title': value,
            'margin': {
                'l': 60,
                'r': 10,
                't': 40,
                'b': 60
            }
        }
    }

if __name__ == '__main__':
    app.run(debug=True)

For more info on Dash Enterprise, see the docs. As usual, a summary of the pros and cons:

Pros:

  • Well maintained enterprise solution with plenty of support
  • Allows users to login via SSO

Cons:

  • Requires additional code and packages to your app
  • Only useful if your app or company is already using Dash Enterprise
  • Paid service

dash-flask-login

Dash-flask-login, created by Rafael Miquelino, is an example Flask authentication layer on top of your Dash application.

Note: This repo is no longer maintained so some parts may be outdated.

Pay special attention to these files:

The README.md doesn’t provide succinct instructions to incorporate these modules into your code, so it will take some tinkering to duplicate this example in your own app. However, if you’re already comfortable with Flask and looking for a more extensive authentication system, this could be a great example to base your application structure on.

Pros:

  • Built using open-source tools
  • Completely free to use
  • Sample code and app structure

Cons:

  • May contain outdated code since it’s no longer maintained
  • Minimal documentation
  • Lots of code to add
  • Need to incorporate a whole different framework (Flask)

Conclusion

That’s it! In this article we compared methods of adding authentication to your Dash app:

  • Ploomber Cloud
  • dash-auth
  • dash-enterprise-auth
  • dash-flask-login

dash-auth and dash-enterprise-auth are both great options created by the original Dash developers, but require adding code to your application. dash-flask-login provides an extensive example with incorporates Flask. Ploomber Cloud, however, secures and deploys your app in one step, with no additional code required. The username and password allow you to share your app to the right people (and only the right people) with minimal hassle.

Deploy Dash Apps with Ploomber

Recent Articles

Try Ploomber Cloud Now

Get Started
*