Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
153 lines (126 loc) · 5.88 KB
/
Copy pathapp.py
File metadata and controls
153 lines (126 loc) · 5.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
from flask import Flask, render_template, redirect, url_for, session, request
import os
import uuid
import msal
from datetime import datetime, timedelta, timezone
from dotenv import load_dotenv
app = Flask(__name__)
# MS Azure login info -- can alternatively move this info to a separate 'config.py' file and create instance of it here. prob better security
app.secret_key = os.environ.get("FLASK_SECRET_KEY")
CLIENT_ID = os.environ.get("AZURE_CLIENT_ID")
CLIENT_SECRET = os.environ.get("AZURE_CLIENT_SECRET")
TENANT_ID = os.environ.get("AZURE_TENANT_ID")
AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}"
SCOPE = ["User.Read"]
SESSION_TIMEOUT = timedelta(minutes=1)
# home page
@app.route('/') # route protection. looks for this exact URL
def home():
return render_template('index.html')
"""
using single-tenant-only option to sim school SSO since they have a db of all student
logins. This means only recognized n manually inserted users will be allowed on this
app. For testing, Azure Active Directory owner will add specific test user to Directory
-- make a testing MS acc for this for security of personal MS accounts.
FOR NOW USE: warriortesteruser1@raulesquerra18gmail.onmicrosoft.com. credentials in .env
API MESSAGE SHOWS WHEN NOT ADDED TO DIR: 'AADSTS50020: User account '<user email>' from identity provider 'live.com' does not exist
in tenant 'Default Directory' and cannot access the application 'fe0e0a8f-50e2-47e6-a8a3-17489660c3d0'(warrior-training-grounds) in
that tenant.The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure
Active Directory user account.
"""
# signin page using personal MS Azure Entra ID
@app.route('/signin') # route protection
def signin():
session["state"] = str(uuid.uuid4()) # gen a state value for Cross-Site Request Forgery (CSRF)-attacks protection
# build auth url with gen'd state
auth_url = _build_msal_app().get_authorization_request_url(
SCOPE,
state=session["state"],
redirect_uri=url_for("callback", _external=True) # match callback to user-initiated session. external url
)
return redirect(auth_url)
# user dashboard ONLY after signing in
@app.route('/dashboard') # route protection
def dashboard():
if "user" not in session:
return redirect(url_for('signin'))
user = session["user"] # retrieve auth user's ID token claims from session
username = user.get("name") # extract display name claim from token data
return render_template('dashboard.html', username=username) # render html template and pass username with it for referncing in html
@app.route('/signout') # route protection
def signout():
if "user" not in session:
return redirect(url_for('signin'))
session.clear() # terminate user session for Grounds app
# log user from MS
logout_url = (
f"{AUTHORITY}/oauth2/v2.0/logout"
f"?post_logout_redirect_uri={url_for('home', _external=True)}"
)
return redirect(logout_url)
@app.route("/inactivity_signout")
def inactivity_signout():
return render_template("inactivity-signout.html", authority=AUTHORITY)
# OAuth re-entry point. callback securely receives proof of auth, validates it, exchanges it for tokens, creates a session, hands control back to app.
@app.route('/callback') # route protection
def callback():
# if user state was gen'd by uuid and matches with requested state, then we fine. inverse of this results in error 400
if request.args.get("state") != session.get("state"):
return "State mismatch", 400
code = request.args.get("code") # one-time MS auth code
# code + client secret validated by MS. exchage code for tokens: ID, Access, Refresh
result = _build_msal_app().acquire_token_by_authorization_code(
code,
scopes=SCOPE,
redirect_uri=url_for("callback", _external=True)
)
# auth confirmation
if "id_token_claims" in result:
session["user"] = result["id_token_claims"] # create authenticated app session
session["last_activity"] = datetime.now(timezone.utc).isoformat() # inactivity counter
return redirect(url_for("dashboard"))
return "Login failed"
# OAuth compelte
"""
from msal library documentation:
ClientApplication/ ConfidentialClientApplication(
client_id,
client_credential=None,
authority=None,
validate_authority=True,
token_cache=None,
http_client=None,
verify=True,
proxies=None,
timeout=None,
client_claims=None,
app_name=None,
app_version=None,
client_capabilities=None,
azure_region=None,
exclude_scopes=None,
http_cache=None,
instance_discovery=None,
allow_broker=None,
enable_pii_log=None,
oidc_authority=None)
"""
# creates auth URLs, exchanges auth code for tokens, caches tokens. MSAL client for api requests
def _build_msal_app(cache=None):
return msal.ConfidentialClientApplication(
CLIENT_ID,
authority=AUTHORITY,
client_credential=CLIENT_SECRET,
token_cache=cache # cache token so user doesnt havce to log back in. must manually sign out
)
@app.before_request
def check_inactivity():
if "user" in session:
last_activity = session.get("last_activity") # set last activity
if last_activity:
last_activity = datetime.fromisoformat(session["last_activity"]) # update request after every user interaction. reset inactivity timer
# inactivity logic: if most recent activity - last activity > timeout constant
if datetime.now(timezone.utc) - last_activity > SESSION_TIMEOUT:
session.clear()
return redirect(url_for("inactivity_signout"))
session["last_activity"] = datetime.now(timezone.utc).isoformat() # update last activity