-
Notifications
You must be signed in to change notification settings - Fork 0
/
okta_client.py
232 lines (181 loc) · 6.86 KB
/
okta_client.py
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
from flask import Flask, session, request, redirect
#from flask_session import Session
import pycurl
from io import BytesIO
import urllib
import json
import base64
import pprint
import random
import os
import client_config
app = Flask(__name__)
app.secret_key = os.urandom(28)
pp = pprint.PrettyPrinter(indent=4)
@app.route('/')
def hello():
if (request.args.get('action') and request.args.get('action') == 'login'):
return login()
elif (request.args.get('action') and request.args.get('action') == 'logout'):
return logout()
elif request.args.get('code'):
return exchange_token()
elif (request.args.get('action') and request.args.get('action') == 'profile'):
return get_profile()
elif (request.args.get('action') and request.args.get('action') == 'users'):
return get_users()
elif (request.args.get('action') and request.args.get('action') == 'messages'):
return get_messages()
elif (request.args.get('action') == None):
return is_logged_in()
def is_logged_in():
the_response = 'No Response'
if(session.get('user_id',None)):
the_response += '<h3> Logged In </h3> '
the_response += '<p>User ID: '+ session.get('user_id') +'</p> '
the_response += '<p>Email: '+ session.get('preferred_username') +'</p> '
the_response += '<p><a href=" ?action=users">Get Users With SSWS Token</a></p>'
the_response += '<p><a href=" ?action=messages">Get Messages from API Server</a></p>'
the_response += '<p><a href="?action=logout">Log Out</a></p>'
the_response += '<h3> ID Token </h3> '
the_response += '<pre> '
data = api_request(client_config.user_info_url)
the_response += str(data)
the_response += '</pre> '
else:
the_response = """
<h3> Not Logged In </h3>
<p><a href="?action=login">Log In</a></p>
"""
return the_response
def login():
session['state'] = str(random.getrandbits(128))
session['access_token'] = None
params = {
'scope' : 'openid profile okta.myAccount.profile.manage',
'client_id': client_config.okta_client_id,
'redirect_uri': client_config.base_url,
'state' : session['state'],
'response_type' : 'code'
}
return redirect(client_config.authorize_url+'?' + urllib.parse.urlencode(params),302)
def logout():
session['access_token'] = None
session['user_id'] = None
return redirect(client_config.base_url,302)
def exchange_token():
if (request.args.get('state',None) == None) or (session.get('state',"no session state").strip() != request.args.get('state', "no request state").strip()):
return redirect(client_config.base_url + '?error=invalid_state',302)
#Exchange auth token for access token
post_params = {
'grant_type': 'authorization_code',
'client_id' : client_config.okta_client_id,
'client_secret' : client_config.okta_client_secret,
'redirect_uri': client_config.base_url,
'code' : request.args.get('code'),
'state' : session.get('state',None)
}
data = api_request(client_config.token_url,post_params)
pp.pprint('Data: ')
pp.pprint(data)
jwt = data['id_token'].split('.')
pp.pprint('JWT: ')
pp.pprint(jwt)
#check padding
padding=''
if len(jwt[1]) % 4:
# not a multiple of 4, add padding:
padding += '=' * (4 - len(padding) % 4)
user_info = json.loads(base64.b64decode(jwt[1]+padding))
pp.pprint('use_info: ')
pp.pprint(user_info)
session['user_id'] = user_info['sub']
session['preferred_username'] = user_info['preferred_username']
session['access_token'] = data['access_token']
session['id_token'] = data['id_token']
session['user_info'] = user_info
return redirect( client_config.base_url,302)
def get_profile():
the_response =''
params = {
#'sort': 'created',
#'direction' : 'desc'
}
profile = api_request(client_config.api_url_base + 'idp/myaccount/profile?' + urllib.parse.urlencode(params))
the_response = str(profile)
if (request.args.get('action') == None):
if (session.get('access_token',None)):
the_response += """
<h3>Logged In</h3>
<p><a href="?action=repos"> View Repos</a>
<p><a href="?action=logout"> Log Out</a>
"""
else:
the_response += """
<h3>Not Logged In</h3>
<p><a href="?action=login"> Log In</a>
"""
return the_response
def get_users():
the_response =''
params = {
#'sort': 'created',
#'direction' : 'desc'
}
profile = api_request(client_config.api_url_base + '/api/v1/users?' + urllib.parse.urlencode(params), ssws=client_config.okta_ssws_token)
the_response = str(profile)
if (request.args.get('action') == None):
if (session.get('access_token',None)):
the_response += """
<h3>Logged In</h3>
<p><a href="?action=repos"> View Repos</a>
<p><a href="?action=logout"> Log Out</a>
"""
else:
the_response += """
<h3>Not Logged In</h3>
<p><a href="?action=login"> Log In</a>
"""
return the_response
#Test API Access
def get_messages():
the_response =''
params = {
#'sort': 'created',
#'direction' : 'desc'
}
messages = api_request(client_config.resource_server_url + '/api/messages')
the_response = str(messages)
if (request.args.get('action') == None):
if (session.get('access_token',None)):
the_response += """
<h3>Logged In</h3>
<p><a href="?action=repos"> View Repos</a>
<p><a href="?action=logout"> Log Out</a>
"""
else:
the_response += """
<h3>Not Logged In</h3>
<p><a href="?action=login"> Log In</a>
"""
return the_response
def api_request(url, post = None , headers = [], ssws=None):
crl= pycurl.Curl()
crl.setopt(crl.URL, url)
crl.setopt(pycurl.VERBOSE, 1)
if post:
crl.setopt(crl.POSTFIELDS,urllib.parse.urlencode(post))
headers = [
'Accept: application/json; okta-version=1.0.0',
'User-Agent: https://example-app.com'
]
if(ssws):
headers += ['Authorization: SSWS '+ssws]
elif session.get("access_token",None):
headers += ['Authorization: Bearer '+session.get("access_token",None)]
crl.setopt(crl.HTTPHEADER, headers)
response = crl.perform_rs()
print('response from curl is : '+response)
return json.loads(response)
if __name__ == '__main__':
app.run(host='localhost', port='5000', debug=True)