This repository has been archived by the owner on Apr 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generic.py
164 lines (130 loc) · 4.91 KB
/
generic.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
"""
Custom Authenticator to use generic OAuth2 with JupyterHub
"""
import json
import os
import base64
import urllib
from tornado.auth import OAuth2Mixin
from tornado import gen, web
from tornado.httputil import url_concat
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from jupyterhub.auth import LocalAuthenticator
from traitlets import Unicode, Dict, Bool
from .oauth2 import OAuthLoginHandler, OAuthenticator
class GenericEnvMixin(OAuth2Mixin):
_OAUTH_ACCESS_TOKEN_URL = os.environ.get('OAUTH2_TOKEN_URL', '')
_OAUTH_AUTHORIZE_URL = os.environ.get('OAUTH2_AUTHORIZE_URL', '')
class GenericLoginHandler(OAuthLoginHandler, GenericEnvMixin):
pass
class GenericOAuthenticator(OAuthenticator):
login_service = Unicode(
"GenericOAuth2",
config=True
)
login_handler = GenericLoginHandler
userdata_url = Unicode(
os.environ.get('OAUTH2_USERDATA_URL', ''),
config=True,
help="Userdata url to get user data login information"
)
token_url = Unicode(
os.environ.get('OAUTH2_TOKEN_URL', ''),
config=True,
help="Access token endpoint URL"
)
extra_params = Dict(
os.environ.get('OAUTH2_AUTHENTICATION_PARAMS', {}),
help="Extra parameters for first POST request"
).tag(config=True)
username_key = Unicode(
os.environ.get('OAUTH2_USERNAME_KEY', 'username'),
config=True,
help="Userdata username key from returned json for USERDATA_URL"
)
userdata_params = Dict(
os.environ.get('OAUTH2_USERDATA_PARAMS', {}),
help="Userdata params to get user data login information"
).tag(config=True)
userdata_method = Unicode(
os.environ.get('OAUTH2_USERDATA_METHOD', 'GET'),
config=True,
help="Userdata method to get user data login information"
)
tls_verify = Bool(
os.environ.get('OAUTH2_TLS_VERIFY', 'True').lower() in {'true', '1'},
config=True,
help="Disable TLS verification on http request"
)
@gen.coroutine
def authenticate(self, handler, data=None):
code = handler.get_argument("code")
# TODO: Configure the curl_httpclient for tornado
http_client = AsyncHTTPClient()
params = dict(
redirect_uri=self.get_callback_url(handler),
code=code,
grant_type='authorization_code'
)
params.update(self.extra_params)
if self.token_url:
url = self.token_url
else:
raise ValueError("Please set the OAUTH2_TOKEN_URL environment variable")
b64key = base64.b64encode(
bytes(
"{}:{}".format(self.client_id, self.client_secret),
"utf8"
)
)
headers = {
"Accept": "application/json",
"User-Agent": "JupyterHub",
"Authorization": "Basic {}".format(b64key.decode("utf8"))
}
req = HTTPRequest(url,
method="POST",
headers=headers,
validate_cert=self.tls_verify,
body=urllib.parse.urlencode(params) # Body is required for a POST...
)
resp = yield http_client.fetch(req)
resp_json = json.loads(resp.body.decode('utf8', 'replace'))
access_token = resp_json['access_token']
refresh_token = resp_json.get('refresh_token', None)
token_type = resp_json['token_type']
scope = resp_json.get('scope', '')
if (isinstance(scope, str)):
scope = scope.split(' ')
# Determine who the logged in user is
headers = {
"Accept": "application/json",
"User-Agent": "JupyterHub",
"Authorization": "{} {}".format(token_type, access_token)
}
if self.userdata_url:
url = url_concat(self.userdata_url, self.userdata_params)
else:
raise ValueError("Please set the OAUTH2_USERDATA_URL environment variable")
req = HTTPRequest(url,
method=self.userdata_method,
headers=headers,
validate_cert=self.tls_verify,
)
resp = yield http_client.fetch(req)
resp_json = json.loads(resp.body.decode('utf8', 'replace'))
if not resp_json.get(self.username_key):
self.log.error("OAuth user contains no key %s: %s", self.username_key, resp_json)
return
return {
'name': resp_json.get(self.username_key),
'auth_state': {
'access_token': access_token,
'refresh_token': refresh_token,
'oauth_user': resp_json,
'scope': scope,
}
}
class LocalGenericOAuthenticator(LocalAuthenticator, GenericOAuthenticator):
"""A version that mixes in local system user creation"""
pass