-
Notifications
You must be signed in to change notification settings - Fork 1
/
aiohttp_server.py
221 lines (171 loc) · 7.18 KB
/
aiohttp_server.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
import logging
import os
import signal
import sys
from wsgiref.simple_server import WSGIRequestHandler, make_server
sys.path.insert(0, os.path.abspath(os.path.realpath(__file__) + '/../../../'))
if sys.version_info >= (3, 5, 3):
from multiprocessing import Process
from urllib.request import urlopen
else:
sys.stderr.write("You need python 3.5.3+ to run this script\n")
exit(1)
import aiohttp.web
from oauth2 import Provider
from oauth2.compatibility import json, parse_qs, urlencode
from oauth2.error import UserNotAuthenticated
from oauth2.grant import AuthorizationCodeGrant
from oauth2.store.memory import ClientStore, TokenStore
from oauth2.tokengenerator import Uuid4TokenGenerator
from oauth2.web import AuthorizationCodeGrantSiteAdapter
from oauth2.web.aiohttp import OAuth2Handler
logging.basicConfig(level=logging.DEBUG)
class ClientRequestHandler(WSGIRequestHandler):
"""
Request handler that enables formatting of the log messages on the console.
This handler is used by the client application.
"""
def address_string(self):
return "client app"
class TestSiteAdapter(AuthorizationCodeGrantSiteAdapter):
"""
This adapter renders a confirmation page so the user can confirm the auth
request.
"""
CONFIRMATION_TEMPLATE = """
<html>
<body>
<p>
<a href="{url}&confirm=1">confirm</a>
</p>
<p>
<a href="{url}&confirm=0">deny</a>
</p>
</body>
</html>
"""
def render_auth_page(self, request, response, environ, scopes, client):
page_url = request.path + "?" + request.query_string
response.body = self.CONFIRMATION_TEMPLATE.format(url=page_url)
return response
def authenticate(self, request, environ, scopes, client):
example_user_id = 123
example_ext_data = {}
if request.method == "GET":
if request.get_param("confirm") == "1":
return example_ext_data, example_user_id
raise UserNotAuthenticated
def user_has_denied_access(self, request):
if request.method == "GET":
if request.get_param("confirm") == "0":
return True
return False
class ClientApplication(object):
"""
Very basic application that simulates calls to the API of the
oauth2-stateless app.
"""
callback_url = "http://localhost:8080/callback"
client_id = "abc"
client_secret = "xyz"
api_server_url = "http://localhost:8081"
def __init__(self):
self.access_token_result = None
self.access_token = None
self.auth_token = None
self.token_type = ""
def __call__(self, env, start_response):
if env["PATH_INFO"] == "/app":
status, body, headers = self._serve_application(env)
elif env["PATH_INFO"] == "/callback":
status, body, headers = self._read_auth_token(env)
else:
status = "301 Moved"
body = ""
headers = {"Location": "/app"}
start_response(status, [(header, val) for header, val in headers.items()])
return [body.encode('utf-8')]
def _request_access_token(self):
print("Requesting access token...")
post_params = {"client_id": self.client_id,
"client_secret": self.client_secret,
"code": self.auth_token,
"grant_type": "authorization_code",
"redirect_uri": self.callback_url}
token_endpoint = self.api_server_url + "/token"
token_result = urlopen(token_endpoint, urlencode(post_params).encode('utf-8'))
result = json.loads(token_result.read().decode('utf-8'))
self.access_token_result = result
self.access_token = result["access_token"]
self.token_type = result["token_type"]
confirmation = "Received access token '%s' of type '%s'" % (self.access_token, self.token_type)
print(confirmation)
return "302 Found", "", {"Location": "/app"}
def _read_auth_token(self, env):
print("Receiving authorization token...")
query_params = parse_qs(env["QUERY_STRING"])
if "error" in query_params:
location = "/app?error=" + query_params["error"][0]
return "302 Found", "", {"Location": location}
self.auth_token = query_params["code"][0]
print("Received temporary authorization token '%s'" % (self.auth_token,))
return "302 Found", "", {"Location": "/app"}
def _request_auth_token(self):
print("Requesting authorization token...")
auth_endpoint = self.api_server_url + "/authorize"
query = urlencode({"client_id": "abc",
"redirect_uri": self.callback_url,
"response_type": "code"})
location = "%s?%s" % (auth_endpoint, query)
return "302 Found", "", {"Location": location}
def _serve_application(self, env):
query_params = parse_qs(env["QUERY_STRING"])
if ("error" in query_params and query_params["error"][0] == "access_denied"):
return "200 OK", "User has denied access", {}
if self.access_token_result is None:
if self.auth_token is None:
return self._request_auth_token()
return self._request_access_token()
confirmation = "Current access token '%s' of type '%s'" % (self.access_token, self.token_type)
return "200 OK", str(confirmation), {}
def run_app_server():
app = ClientApplication()
try:
httpd = make_server('', 8080, app, handler_class=ClientRequestHandler)
print("Starting Client app on http://localhost:8080/...")
httpd.serve_forever()
except KeyboardInterrupt:
httpd.server_close()
def run_auth_server():
client_store = ClientStore()
client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=["http://localhost:8080/callback"])
token_store = TokenStore()
provider = Provider(access_token_store=token_store,
auth_code_store=token_store, client_store=client_store,
token_generator=Uuid4TokenGenerator())
provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter()))
try:
app = aiohttp.web.Application()
handler = OAuth2Handler(provider)
app.router.add_get(provider.authorize_path, handler.dispatch_request)
app.router.add_post(provider.authorize_path, handler.post_dispatch_request)
app.router.add_post(provider.token_path, handler.post_dispatch_request)
aiohttp.web.run_app(app, host='127.0.0.1', port=8081)
print("Starting OAuth2 server on http://localhost:8081/...")
except KeyboardInterrupt:
aiohttp.web.close()
def main():
auth_server = Process(target=run_auth_server)
auth_server.start()
app_server = Process(target=run_app_server)
app_server.start()
print("Access http://localhost:8080/app in your browser")
def sigint_handler(signal, frame):
print("Terminating servers...")
auth_server.terminate()
auth_server.join()
app_server.terminate()
app_server.join()
signal.signal(signal.SIGINT, sigint_handler)
if __name__ == "__main__":
main()