|
1 | 1 | import uuid
|
2 |
| -import flask |
3 | 2 | import requests
|
4 |
| -from flask import Flask, render_template, session, request |
5 |
| -from flask_session import Session |
| 3 | +from flask import Flask, render_template, session, request, redirect, url_for |
| 4 | +from flask_session import Session # https://pythonhosted.org/Flask-Session |
6 | 5 | import msal
|
7 | 6 | import app_config
|
8 | 7 |
|
9 |
| -sess = Session() |
10 |
| -app = Flask(__name__) |
11 |
| -app.config.from_object('config.Config') |
12 |
| -sess.init_app(app) |
13 |
| -cache = msal.SerializableTokenCache() |
14 |
| -application = msal.ConfidentialClientApplication( |
15 |
| - app_config.CLIENT_ID, authority=app_config.AUTHORITY, |
16 |
| - client_credential=app_config.CLIENT_SECRET, |
17 |
| - token_cache=cache) |
18 |
| - |
19 |
| - |
20 |
| -def set_cache(): |
21 |
| - if cache.has_state_changed: |
22 |
| - session[request.cookies.get("session")] = cache.serialize() |
23 |
| - |
24 |
| - |
25 |
| -def check_cache(): |
26 |
| - # Checking token cache for accounts |
27 |
| - result = None |
28 |
| - accounts = application.get_accounts() |
29 | 8 |
|
30 |
| - # Trying to acquire token silently |
31 |
| - if accounts: |
32 |
| - result = application.acquire_token_silent(app_config.SCOPE, account=accounts[0]) |
33 |
| - return result |
34 |
| - |
35 |
| - |
36 |
| -def get_graph_info(result): |
37 |
| - if 'access_token' not in result: |
38 |
| - return flask.redirect(flask.url_for('index')) |
39 |
| - endpoint = 'https://graph.microsoft.com/v1.0/me/' |
40 |
| - http_headers = {'Authorization': 'Bearer ' + result['access_token'], |
41 |
| - 'User-Agent': 'msal-python-sample', |
42 |
| - 'Accept': 'application/json', |
43 |
| - 'Content-Type': 'application/json', |
44 |
| - 'client-request-id': str(uuid.uuid4())} |
45 |
| - graph_data = requests.get(endpoint, headers=http_headers, stream=False).json() |
46 |
| - return graph_data |
| 9 | +app = Flask(__name__) |
| 10 | +app.config.from_object(app_config) |
| 11 | +Session(app) |
47 | 12 |
|
48 | 13 |
|
49 |
| -@app.route('/') |
| 14 | +@app.route("/") |
50 | 15 | def index():
|
51 |
| - return render_template("index.html") |
52 |
| - |
53 |
| - |
54 |
| -@app.route('/processing') |
55 |
| -def processing(): |
56 |
| - # Initializing |
57 |
| - is_session = session.get(request.cookies.get("session")) |
58 |
| - if is_session is None: |
59 |
| - session[request.cookies.get("session")] = '' |
60 |
| - cache.deserialize(session.get(request.cookies.get("session"))) |
61 |
| - return flask.redirect(flask.url_for('my_info')) |
62 |
| - |
63 |
| - |
64 |
| -@app.route('/my_info') |
65 |
| -def my_info(): |
66 |
| - result = check_cache() |
67 |
| - if result: |
68 |
| - graph_result = get_graph_info(result) |
69 |
| - return flask.render_template('display.html', auth_result=graph_result, cond="logout") |
70 |
| - else: |
71 |
| - return flask.render_template('display.html', auth_result="You are not signed in", cond="") |
72 |
| - |
73 |
| - |
74 |
| -@app.route('/authenticate') |
75 |
| -def authenticate(): |
76 |
| - # Call to the authorize endpoint |
77 |
| - auth_state = str(uuid.uuid4()) |
78 |
| - session[(request.cookies.get("session")+'state')] = auth_state |
79 |
| - authorization_url = application.get_authorization_request_url(app_config.SCOPE, state=auth_state, |
80 |
| - redirect_uri=app_config.REDIRECT_URI) |
81 |
| - resp = flask.Response(status=307) |
82 |
| - resp.headers['location'] = authorization_url |
83 |
| - return resp |
84 |
| - |
85 |
| - |
86 |
| -@app.route("/getAToken") |
87 |
| -def main_logic(): |
88 |
| - code = flask.request.args['code'] |
89 |
| - state = flask.request.args['state'] |
90 |
| - # Raising error if state does not match |
91 |
| - if state != session[(request.cookies.get("session")+'state')]: |
92 |
| - raise ValueError("State does not match") |
93 |
| - result = application.acquire_token_by_authorization_code(code, scopes=app_config.SCOPE, |
94 |
| - redirect_uri=app_config.REDIRECT_URI) |
95 |
| - # Updating cache |
96 |
| - set_cache() |
97 |
| - |
98 |
| - # Using access token from result to call Microsoft Graph |
99 |
| - graph_data = get_graph_info(result) |
100 |
| - return flask.render_template('display.html', auth_result=graph_data, cond="logout") |
101 |
| - |
| 16 | + if not session.get("user"): |
| 17 | + return redirect(url_for("login")) |
| 18 | + return render_template('index.html', user=session["user"]) |
| 19 | + |
| 20 | +@app.route("/login") |
| 21 | +def login(): |
| 22 | + 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 |
| 29 | + |
| 30 | +@app.route("/getAToken") # Its absolute URL must match your app's redirect_uri set in AAD |
| 31 | +def authorized(): |
| 32 | + if request.args['state'] != session.get("state"): |
| 33 | + return redirect(url_for("login")) |
| 34 | + cache = _load_cache() |
| 35 | + result = _build_msal_app(cache).acquire_token_by_authorization_code( |
| 36 | + request.args['code'], |
| 37 | + scopes=app_config.SCOPE, # Misspelled scope would cause an HTTP 400 error here |
| 38 | + redirect_uri=url_for("authorized", _external=True)) |
| 39 | + if "error" in result: |
| 40 | + return "Login failure: %s, %s" % ( |
| 41 | + result["error"], result.get("error_description")) |
| 42 | + session["user"] = result.get("id_token_claims") |
| 43 | + _save_cache(cache) |
| 44 | + return redirect(url_for("index")) |
102 | 45 |
|
103 | 46 | @app.route("/logout")
|
104 | 47 | def logout():
|
105 |
| - # Logout |
106 |
| - accounts = application.get_accounts() |
107 |
| - application.remove_account(accounts[0]) |
108 |
| - set_cache() |
109 |
| - return flask.redirect(flask.url_for('index')) |
110 |
| - |
| 48 | + session["user"] = None # Log out from this app from its session |
| 49 | + # session.clear() # If you prefer, this would nuke the user's token cache too |
| 50 | + return redirect( # Also need to logout from Microsoft Identity platform |
| 51 | + "https://login.microsoftonline.com/common/oauth2/v2.0/logout" |
| 52 | + "?post_logout_redirect_uri=" + url_for("index", _external=True)) |
| 53 | + |
| 54 | +@app.route("/graphcall") |
| 55 | +def graphcall(): |
| 56 | + token = _get_token_from_cache(app_config.SCOPE) |
| 57 | + if not token: |
| 58 | + return redirect(url_for("login")) |
| 59 | + graph_data = requests.get( # Use token to call downstream service |
| 60 | + app_config.ENDPOINT, |
| 61 | + headers={'Authorization': 'Bearer ' + token['access_token']}, |
| 62 | + ).json() |
| 63 | + return render_template('display.html', result=graph_data) |
| 64 | + |
| 65 | + |
| 66 | +def _load_cache(): |
| 67 | + cache = msal.SerializableTokenCache() |
| 68 | + if session.get("token_cache"): |
| 69 | + cache.deserialize(session["token_cache"]) |
| 70 | + return cache |
| 71 | + |
| 72 | +def _save_cache(cache): |
| 73 | + if cache.has_state_changed: |
| 74 | + session["token_cache"] = cache.serialize() |
| 75 | + |
| 76 | +def _build_msal_app(cache=None): |
| 77 | + return msal.ConfidentialClientApplication( |
| 78 | + app_config.CLIENT_ID, authority=app_config.AUTHORITY, |
| 79 | + client_credential=app_config.CLIENT_SECRET, token_cache=cache) |
| 80 | + |
| 81 | +def _get_token_from_cache(scope=None): |
| 82 | + cache = _load_cache() # This web app maintains one cache per session |
| 83 | + cca = _build_msal_app(cache) |
| 84 | + accounts = cca.get_accounts() |
| 85 | + if accounts: # So all account(s) belong to the current signed-in user |
| 86 | + result = cca.acquire_token_silent(scope, account=accounts[0]) |
| 87 | + _save_cache(cache) |
| 88 | + return result |
111 | 89 |
|
112 | 90 | if __name__ == "__main__":
|
113 | 91 | app.run()
|
| 92 | + |
0 commit comments