Authentication
Basic Auth
  • Users can not log out of applications
  • Viewers can not create their own account and cannot change their password
  • import dash
    import dash_auth
    import dash_core_components as dcc
    import dash_html_components as html
    import plotly
    
    # Keep this out of source code repository - save in a file or a database
    VALID_USERNAME_PASSWORD_PAIRS = {
        'hello': 'world',
        'lin': 'chen'
    }
    
    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
    
    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
    auth = dash_auth.BasicAuth(
        app,
        VALID_USERNAME_PASSWORD_PAIRS
    )
    
    app.layout = html.Div([
        html.H1('Welcome to the app'),
    ], className='container')
    
    if __name__ == '__main__':
        app.run_server(debug=True)
            
    Get Username
  • Use request of Flask in a callback function to avoid "RuntimeError: Working outside of request context"
  • import dash
    import dash_auth
    import dash_core_components as dcc
    import dash_html_components as html
    from dash.dependencies import Input, Output
    from flask import request
    
    # Keep this out of source code repository - save in a file or a database
    VALID_USERNAME_PASSWORD_PAIRS = {
        'hello': 'world',
        'lin': 'chen'
    }
    
    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
    
    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
    auth = dash_auth.BasicAuth(
        app,
        VALID_USERNAME_PASSWORD_PAIRS
    )
    
    app.layout = html.Div([
        html.H1('Welcome to the app'),
        html.H1(id = 'content'),
        html.Button('Click', id = 'button')
    ], className='container')
    
    @app.callback(
        Output(component_id='content', component_property='children'),
        [Input(component_id='button', component_property='n_clicks')]
    )
    def update_output_div(n_clicks):
        username = request.authorization['username']
        if n_clicks:
            return username
        else:
            return
    
    app.scripts.config.serve_locally = True
    
    if __name__ == '__main__':
        app.run_server(debug=True)
            
    Change Username
  • Type "chrome://restart" to restart Chrome
  • Command + Shift + n to use incognito mode
  • Reference
  • Documentation