Skip to content

Commit 9535205

Browse files
committed
A login.html template, and a _build_auth_url()
1 parent 0ecbd97 commit 9535205

File tree

2 files changed

+29
-8
lines changed

2 files changed

+29
-8
lines changed

app.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,10 @@ def index():
2020
@app.route("/login")
2121
def login():
2222
session["state"] = str(uuid.uuid4())
23-
auth_url = _build_msal_app().get_authorization_request_url(
24-
app_config.SCOPE, # Technically we can use empty list [] to just sign in,
25-
# here we choose to also collect end user consent upfront
26-
state=session["state"],
27-
redirect_uri=url_for("authorized", _external=True))
28-
return "<a href='%s'>Login with Microsoft Identity</a>" % auth_url
23+
# Technically we could use empty list [] as scopes to do just sign in,
24+
# here we choose to also collect end user consent upfront
25+
auth_url = _build_auth_url(scopes=app_config.SCOPE, state=session["state"])
26+
return render_template("login.html", auth_url=auth_url, version=msal.__version__)
2927

3028
@app.route(app_config.REDIRECT_PATH) # Its absolute URL must match your app's redirect_uri set in AAD
3129
def authorized():
@@ -74,11 +72,17 @@ def _save_cache(cache):
7472
if cache.has_state_changed:
7573
session["token_cache"] = cache.serialize()
7674

77-
def _build_msal_app(cache=None):
75+
def _build_msal_app(cache=None, authority=None):
7876
return msal.ConfidentialClientApplication(
79-
app_config.CLIENT_ID, authority=app_config.AUTHORITY,
77+
app_config.CLIENT_ID, authority=authority or app_config.AUTHORITY,
8078
client_credential=app_config.CLIENT_SECRET, token_cache=cache)
8179

80+
def _build_auth_url(authority=None, scopes=None, state=None):
81+
return _build_msal_app(authority=authority).get_authorization_request_url(
82+
scopes or [],
83+
state=state or str(uuid.uuid4()),
84+
redirect_uri=url_for("authorized", _external=True))
85+
8286
def _get_token_from_cache(scope=None):
8387
cache = _load_cache() # This web app maintains one cache per session
8488
cca = _build_msal_app(cache=cache)
@@ -88,6 +92,8 @@ def _get_token_from_cache(scope=None):
8892
_save_cache(cache)
8993
return result
9094

95+
app.jinja_env.globals.update(_build_auth_url=_build_auth_url) # Used in template
96+
9197
if __name__ == "__main__":
9298
app.run()
9399

templates/login.html

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
</head>
6+
<body>
7+
<h1>Microsoft Identity Python Web App</h1>
8+
9+
<li><a href='{{ auth_url }}'>Sign In</a></li>
10+
11+
<hr>
12+
<footer style="text-align: right">Powered by MSAL Python {{ version }}</footer>
13+
</body>
14+
</html>
15+

0 commit comments

Comments
 (0)