Created
April 6, 2023 09:21
-
-
Save kummerer94/9c3e13cb7e3e4c628b8526233a704bfe to your computer and use it in GitHub Desktop.
This is an example for a Dash app that includes AAD auth.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jwt | |
from dash import Dash, Input, Output, html | |
from flask import Flask, redirect, url_for | |
from flask_dance.contrib.azure import azure, make_azure_blueprint | |
from werkzeug.middleware.proxy_fix import ProxyFix | |
def login_required(func): | |
"""Require a login for the given view function.""" | |
def check_authorization(*args, **kwargs): | |
if not azure.authorized or azure.token.get("expires_in") < 0: | |
return redirect(url_for("azure.login")) | |
else: | |
return func(*args, **kwargs) | |
return check_authorization | |
blueprint = make_azure_blueprint( | |
client_id="yourclient", | |
client_secret="yoursecret", | |
tenant="yourtenant", | |
scope=["openid", "email", "profile"], | |
) | |
app = Flask(__name__) | |
app.config["SECRET_KEY"] = "secretkey" | |
app.register_blueprint(blueprint, url_prefix="/login") | |
dash_app = Dash(__name__, server=app) | |
# use this in your production environment since you will otherwise run into problems | |
# https://flask-dance.readthedocs.io/en/v0.9.0/proxies.html#proxies-and-https | |
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1) | |
for view_func in app.view_functions: | |
if not view_func.startswith("azure"): | |
app.view_functions[view_func] = login_required(app.view_functions[view_func]) | |
@dash_app.callback([Output("userid", "children")], [Input("inputdiv", "children")]) | |
def show_user(inputdiv): | |
# no need to verify the token here, that was already done before | |
id_claims = jwt.decode(azure.token.get("id_token"), options={"verify_signature": False}) | |
return [id_claims.get("name")] | |
dash_app.layout = html.Div( | |
children=[ | |
html.H1(children="Hello Dash"), | |
html.Div(children="You are logged in!"), | |
html.Div(id="inputdiv"), | |
html.Div(id="userid"), | |
] | |
) | |
if __name__ == "__main__": | |
dash_app.run_server(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment