keycloak-oauth-system 0.1.0a2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ Thomas Ward <teward@thomas-ward.net>
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.4
2
+ Name: keycloak-oauth-system
3
+ Version: 0.1.0a2
4
+ Summary: Keycloak OAuth handler library that uses programmatic evaluation of callback URLs without the need for a callback server
5
+ Author-email: Thomas Ward <teward@thomas-ward.net>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/teward/KeycloakOAuth.git
8
+ Keywords: oauth,oauth 2.0,keycloak
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Programming Language :: Python :: 3.15
17
+ Classifier: Programming Language :: Python :: 3.16
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ License-File: LICENSE
21
+ License-File: AUTHORS
22
+ Requires-Dist: requests
23
+ Requires-Dist: pyqrcode
24
+ Dynamic: license-file
@@ -0,0 +1,5 @@
1
+ from .auth_code_flow import AuthCodeFlow
2
+ from .client_credentials_flow import ClientCredentialsFlow
3
+ from .device_code_flow import DeviceCodeFlow
4
+
5
+ __version__ = "0.1.0-alpha2"
@@ -0,0 +1,99 @@
1
+ from urllib.parse import parse_qs, urljoin
2
+
3
+ import requests
4
+
5
+ from util import generate_random_string
6
+
7
+
8
+ # noinspection HttpUrlsUsage
9
+ class BaseAuthHandler:
10
+ def __init__(self, auth_server_base_url: str, realm: str, client_id: str, client_secret: str):
11
+ # Initialize a new HTTP requests Session for cookie integrity
12
+ self._session = requests.Session()
13
+
14
+ # Initialize certain static data values we'll need.
15
+ if (not auth_server_base_url.lower().startswith('http://')
16
+ and not auth_server_base_url.lower().startswith('https://')):
17
+ raise ValueError("You did not provide a proper base URL for the Keycloak server you "
18
+ "wish to use. It must start with 'http://' or 'https://'")
19
+ self._auth_server = auth_server_base_url # Keycloak URL
20
+ self._redirect_uri = "http://localhost/callback"
21
+
22
+ # Some values are from input
23
+ self._realm = realm # auth realm in Keycloak
24
+ self.client_id = client_id
25
+ self.client_secret = client_secret
26
+
27
+ # And now we also provide some fetched and calculated items.
28
+ ## _oidc is used to get the OpenID Connect configuration which includes
29
+ ## requisite items for the auth flows. This is stored in _openid_config if
30
+ ## the request returned a 200 OK response.
31
+ _oidc = self._session.get(
32
+ urljoin(self._auth_server, f'/realms/{self.realm}/.well-known/openid-configuration'),
33
+ )
34
+ if _oidc.status_code != 200:
35
+ raise RuntimeError("Could not get requisite information from specified auth server. "
36
+ "Double check the realm you specified.")
37
+ ## We store the OpenID Configuration data here
38
+ self._openid_config = _oidc.json()
39
+
40
+ ## Only instantiate token endpoint which is common to all auth formats
41
+ self._token_endpoint = self._openid_config["token_endpoint"]
42
+
43
+ ## State is not used in every type of request, but it doesn't hurt to generate.
44
+ self._state = generate_random_string(32)
45
+
46
+ @property
47
+ def realm(self) -> str:
48
+ return self._realm
49
+
50
+ @property
51
+ def auth_server(self) -> str:
52
+ return self._auth_server
53
+
54
+ @property
55
+ def token_endpoint(self) -> str:
56
+ return self._token_endpoint
57
+
58
+ @property
59
+ def openid_configuration(self) -> dict:
60
+ return self._openid_config
61
+
62
+
63
+ class BaseAuthParameterGenerator:
64
+ def __init__(self, auth_server: str, realm: str, client_id: str, client_secret: str):
65
+ # Initialize a new HTTP requests Session for cookie integrity
66
+ self._session = requests.Session()
67
+
68
+ # Initialize certain static data values we'll need.
69
+ self._auth_server = auth_server
70
+ self._redirect_uri = "http://localhost/callback"
71
+
72
+ # Some values are from input
73
+ self._realm = realm # auth realm in Keycloak
74
+ self.client_id = client_id
75
+ self.client_secret = client_secret
76
+
77
+ # And now we also provide some fetched and calculated items.
78
+ ## _oidc is used to get the OpenID Connect configuration which includes
79
+ ## requisite items for the auth flows. This is stored in _openid_config if
80
+ ## the request returned a 200 OK response.
81
+
82
+ ## Only instantiate token endpoint which is common to all auth formats
83
+ self._token_endpoint = urljoin(self._auth_server,
84
+ f"/realms/{self._realm}/protocol/openid-connect/token")
85
+
86
+ ## State is not used in every type of request, but it doesn't hurt to generate.
87
+ self._state = generate_random_string(32)
88
+
89
+ @property
90
+ def realm(self) -> str:
91
+ return self._realm
92
+
93
+ @property
94
+ def auth_server(self) -> str:
95
+ return self._auth_server
96
+
97
+ @property
98
+ def token_endpoint(self) -> str:
99
+ return self._token_endpoint
@@ -0,0 +1,214 @@
1
+ from datetime import datetime, timezone
2
+ import html
3
+ import re
4
+ from urllib.parse import urlparse, parse_qs
5
+
6
+ from _base import BaseAuthHandler
7
+ from util import generate_pkce, jwt_decode
8
+
9
+
10
+ class AuthCodeFlow(BaseAuthHandler):
11
+ # noinspection PyTypeChecker
12
+ def __init__(self, auth_server: str, realm: str, client_id: str, client_secret: str,
13
+ user_id: str, user_password: str, use_pkce: bool = False):
14
+ super().__init__(auth_server, realm, client_id, client_secret)
15
+
16
+ # Initialize certain properties as Empty
17
+ self._access_token: str = None
18
+ self._access_token_expiry: datetime = None
19
+ self._refresh_token: str = None
20
+ self._refresh_token_expiry: datetime = None
21
+
22
+ # Auth Code Flow uses the BaseAuthHandler but also has some extra bits we have to do.
23
+ # Namely, we need user credentials, and determine if we need PKCE or not.
24
+
25
+ # Auth Code Flow depends on the authorization endpoint, which is NOT
26
+ # instantiated as a property in the Base Auth handler
27
+ self._authorization_endpoint = self._openid_config["authorization_endpoint"]
28
+
29
+ # We only add PKCE data if it's needed
30
+ if use_pkce:
31
+ self._pkce = generate_pkce()
32
+ else:
33
+ self._pkce = {}
34
+
35
+ # We can now, however, set up dictionaries we'll need later.
36
+ self._user_credentials = {
37
+ "username": user_id,
38
+ "password": user_password
39
+ }
40
+
41
+ self._auth_login_parameters = {
42
+ "response_type": "code",
43
+ "client_id": self.client_id,
44
+ "scope": "openid",
45
+ "redirect_uri": self._redirect_uri,
46
+ "state": self._state
47
+ }
48
+
49
+ self._token_endpoint_base_data = {
50
+ "grant_type": "authorization_code",
51
+ "client_id": self.client_id,
52
+ "client_secret": self.client_secret,
53
+ "redirect_uri": self._redirect_uri,
54
+ }
55
+
56
+ if self._pkce: # This will only work if the dictionary is not empty!
57
+ # If the self._pkce dict is NOT an empty dictionary, then we have to use PKCE
58
+ self._auth_login_parameters["code_challenge"] = self._pkce['challenge']
59
+ self._auth_login_parameters["code_challenge_method"] = "S256"
60
+ self._token_endpoint_base_data["code_verifier"] = self._pkce["verifier"]
61
+
62
+ def __repr__(self):
63
+ struct = ["<KeycloakOAuth.AuthCodeFlow",
64
+ f"pkce={'yes' if self._pkce else 'no'}",
65
+ f"realm={self._realm}",
66
+ f"ClientID={self.client_id}"]
67
+ if self.access_token:
68
+ # noinspection PyUnresolvedReferences
69
+ if self.access_token_expiry < datetime.now(tz=timezone.utc):
70
+ struct.append("access_token=expired")
71
+ else:
72
+ struct.append("access_token=available")
73
+ else:
74
+ struct.append("access_token=empty")
75
+
76
+ if self.refresh_token:
77
+ # noinspection PyUnresolvedReferences
78
+ if self.refresh_token_expiry < datetime.now(tz=timezone.utc):
79
+ struct.append("refresh_token=expired")
80
+ else:
81
+ struct.append("refresh_token=available")
82
+ else:
83
+ struct.append("refresh_token=empty")
84
+
85
+ return " ".join(struct) + ">"
86
+
87
+ @property
88
+ def authorization_endpoint(self) -> str:
89
+ # This is added here because it is not part of the core BaseAuthHandler class
90
+ return self._authorization_endpoint
91
+
92
+ # noinspection PyUnresolvedReferences
93
+ @property
94
+ def access_token(self) -> str | None:
95
+ if self._access_token and self.access_token_expiry < datetime.now(tz=timezone.utc):
96
+ raise RuntimeWarning("WARNING: The retrieved access key is expired.")
97
+ return self._access_token
98
+
99
+ @property
100
+ def access_token_expiry(self) -> datetime | None:
101
+ return self._access_token_expiry
102
+
103
+ # noinspection PyUnresolvedReferences
104
+ @property
105
+ def refresh_token(self) -> str | None:
106
+ if self._refresh_token and self.refresh_token_expiry < datetime.now(tz=timezone.utc):
107
+ raise RuntimeWarning("WARNING: The retrieved refresh key is expired.")
108
+ return self._refresh_token
109
+
110
+ @property
111
+ def refresh_token_expiry(self) -> datetime | None:
112
+ return self._refresh_token_expiry
113
+
114
+ # noinspection PyUnresolvedReferences
115
+ def get_authorization_code(self) -> str:
116
+ login_page = self._session.get(
117
+ self.authorization_endpoint, params=self._auth_login_parameters, allow_redirects=False
118
+ )
119
+ if login_page.status_code != 200:
120
+ raise RuntimeError("Could not get login page or login endpoint URL, invalid response"
121
+ f"code from server: {login_page.status_code}")
122
+
123
+ form_action = html.unescape(
124
+ re.search(r'<form\s+.*?\s+action="(.*?)"',
125
+ login_page.text, re.DOTALL).group(1)
126
+ )
127
+
128
+ auth_resp = self._session.post(
129
+ form_action, data=self._user_credentials, allow_redirects=False
130
+ )
131
+ if auth_resp.status_code not in [300, 301, 302]:
132
+ raise RuntimeError("Unable to get an authorization code with provided login "
133
+ "credentials; possible login failure or invalid creds.")
134
+
135
+ auth_redirect_params = parse_qs(urlparse(auth_resp.headers['Location']).query)
136
+ try:
137
+ auth_code = auth_redirect_params['code'][0]
138
+ except KeyError:
139
+ raise RuntimeError(f"No code in response.")
140
+
141
+ return auth_code
142
+
143
+ def get_tokens_from_code(self, code: str) -> dict:
144
+ data = dict(self._token_endpoint_base_data)
145
+ data['code'] = code
146
+
147
+ token_request = self._session.post(
148
+ self.token_endpoint, data=data, allow_redirects=False
149
+ )
150
+ if token_request.status_code != 200:
151
+ raise RuntimeError("Unable to exchange authorization code for token.")
152
+
153
+ # Store current access token and expiry in object
154
+ self._access_token = token_request.json()['access_token']
155
+ self._access_token_expiry = datetime.fromtimestamp(
156
+ int(jwt_decode(self._access_token)['exp']), tz=timezone.utc
157
+ )
158
+
159
+ # Store current refresh token and expiry in object
160
+ self._refresh_token = token_request.json()['refresh_token']
161
+ self._refresh_token_expiry = datetime.fromtimestamp(
162
+ int(jwt_decode(self._refresh_token)['exp']), tz=timezone.utc
163
+ )
164
+
165
+ return token_request.json()
166
+
167
+ # noinspection PyTypeChecker
168
+ def refresh_access_token(self, refresh_token: str):
169
+ # First we need to check the refresh token, which is a JWT,
170
+ # and its embedded 'exp' UNIX timestamp against now.
171
+ expiry = datetime.fromtimestamp(
172
+ int(jwt_decode(refresh_token)['exp']),
173
+ tz=timezone.utc
174
+ )
175
+ if expiry < datetime.now(tz=timezone.utc):
176
+ raise RuntimeError("Your refresh token has expired. You must start over with "
177
+ "the entire OAuth flow from the beginning.")
178
+
179
+ data = {
180
+ "refresh_token": refresh_token,
181
+ "grant_type": "refresh_token",
182
+ "client_id": self.client_id,
183
+ "client_secret": self.client_secret
184
+ }
185
+
186
+ refresh_req = self._session.post(
187
+ self.token_endpoint, data=data, allow_redirects=False
188
+ )
189
+ if refresh_req.status_code != 200:
190
+ raise RuntimeError("Unable to refresh token.")
191
+
192
+ # Store current access token and expiry in object
193
+ self._access_token = refresh_req.json()['access_token']
194
+ self._access_token_expiry = datetime.fromtimestamp(
195
+ int(jwt_decode(self.access_token)['exp']), tz=timezone.utc
196
+ )
197
+
198
+ # Store current refresh token and expiry in object
199
+ self._refresh_token = refresh_req.json()['refresh_token']
200
+ self._refresh_token_expiry = datetime.fromtimestamp(
201
+ int(jwt_decode(self.refresh_token)['exp']), tz=timezone.utc
202
+ )
203
+
204
+ return refresh_req.json()
205
+
206
+ def run_auth_flow(self) -> dict:
207
+ auth_code = self.get_authorization_code()
208
+ tokens = self.get_tokens_from_code(auth_code)
209
+
210
+ return tokens
211
+
212
+ # noinspection PyTypeChecker
213
+ def run_refresh_flow(self) -> dict:
214
+ return self.refresh_access_token(self.refresh_token)
@@ -0,0 +1,133 @@
1
+ from datetime import datetime, timezone
2
+
3
+ from _base import BaseAuthHandler
4
+ from util import jwt_decode
5
+
6
+
7
+ class ClientCredentialsFlow(BaseAuthHandler):
8
+ # noinspection PyTypeChecker
9
+ def __init__(self, auth_server: str, realm: str, client_id: str, client_secret: str):
10
+ super().__init__(auth_server, realm, client_id, client_secret)
11
+
12
+ # Initialize certain properties
13
+ self._access_token: str = None
14
+ self._access_token_expiry: datetime = None
15
+ self._refresh_token: str = None
16
+ self._refresh_token_expiry: datetime = None
17
+
18
+ # Get the token endpoint.
19
+ self._token_endpoint = self._openid_config["token_endpoint"]
20
+
21
+ self._auth_parameters = {
22
+ "grant_type": "client_credentials",
23
+ "client_id": client_id,
24
+ "client_secret": client_secret
25
+ }
26
+
27
+ def __repr__(self):
28
+ struct = ["<KeycloakOAuth.ClientCredentialFlow",
29
+ f"realm={self._realm}",
30
+ f"ClientID={self.client_id}"]
31
+ if self._access_token:
32
+ if self._access_token_expiry < datetime.now(tz=timezone.utc):
33
+ struct.append("access_token=expired")
34
+ else:
35
+ struct.append("access_token=available")
36
+ else:
37
+ struct.append("access_token=empty")
38
+
39
+ if self._refresh_token:
40
+ if self._refresh_token_expiry < datetime.now(tz=timezone.utc):
41
+ struct.append("refresh_token=expired")
42
+ else:
43
+ struct.append("refresh_token=available")
44
+ else:
45
+ struct.append("refresh_token=empty")
46
+
47
+ return " ".join(struct) + ">"
48
+
49
+ @property
50
+ def token_endpoint(self) -> str:
51
+ return self._token_endpoint
52
+
53
+ # noinspection PyUnresolvedReferences
54
+ @property
55
+ def access_token(self) -> str | None:
56
+ if self._access_token and self._access_token_expiry < datetime.now(tz=timezone.utc):
57
+ raise RuntimeWarning("WARNING: The retrieved access key is expired.")
58
+ return self._access_token
59
+
60
+ @property
61
+ def access_token_expiry(self) -> datetime | None:
62
+ return self._access_token_expiry
63
+
64
+ # noinspection PyUnresolvedReferences
65
+ @property
66
+ def refresh_token(self) -> str | None:
67
+ if self._refresh_token and self.refresh_token_expiry < datetime.now(tz=timezone.utc):
68
+ raise RuntimeWarning("WARNING: The retrieved refresh key is expired.")
69
+ return self._refresh_token
70
+
71
+ @property
72
+ def refresh_token_expiry(self) -> datetime | None:
73
+ return self._refresh_token_expiry
74
+
75
+ def get_tokens(self) -> dict:
76
+ data = dict(self._auth_parameters)
77
+ token_request = self._session.post(
78
+ self.token_endpoint, data=data, allow_redirects=False
79
+ )
80
+
81
+ # Store current access token and expiry in object
82
+ self._access_token = token_request.json()['access_token']
83
+ self._access_token_expiry = datetime.fromtimestamp(
84
+ int(jwt_decode(self._access_token)['exp']), tz=timezone.utc
85
+ )
86
+
87
+ # Store current refresh token and expiry in object
88
+ self._refresh_token = token_request.json()['refresh_token']
89
+ self._refresh_token_expiry = datetime.fromtimestamp(
90
+ int(jwt_decode(self._refresh_token)['exp']), tz=timezone.utc
91
+ )
92
+
93
+ return token_request.json()
94
+
95
+ # noinspection PyTypeChecker
96
+ def _refresh_access_token(self, refresh_token: str) -> dict:
97
+ if not self._access_token:
98
+ raise RuntimeError("You do not have a refresh token. Have you run through "
99
+ "the client credentials flow yet?")
100
+
101
+ if self._refresh_token_expiry < datetime.now(tz=timezone.utc):
102
+ raise RuntimeError("Your refresh token has expired. You must start over with "
103
+ "the entire OAuth flow from the beginning.")
104
+
105
+ data = {
106
+ "refresh_token": refresh_token,
107
+ "grant_type": "refresh_token",
108
+ "client_id": self.client_id,
109
+ "client_secret": self.client_secret
110
+ }
111
+
112
+ refresh_req = self._session.post(self.token_endpoint, data=data, allow_redirects=False)
113
+
114
+ if refresh_req.status_code != 200:
115
+ raise RuntimeError("Unable to refresh token.")
116
+
117
+ # Store current access token and expiry.
118
+ self._access_token = refresh_token.json()["access_token"]
119
+ self._access_token_expiry = datetime.fromtimestamp(
120
+ int(jwt_decode(self.access_token)['exp']), tz=timezone.utc
121
+ )
122
+
123
+ # Store current refresh token and expiry in object
124
+ self._refresh_token = refresh_req.json()['refresh_token']
125
+ self._refresh_token_expiry = datetime.fromtimestamp(
126
+ int(jwt_decode(self.refresh_token)['exp']), tz=timezone.utc
127
+ )
128
+
129
+ return refresh_req.json()
130
+
131
+ # noinspection PyTypeChecker
132
+ def refresh_access_token(self):
133
+ return self._refresh_access_token(self.refresh_token)
@@ -0,0 +1,78 @@
1
+ from datetime import datetime, timezone
2
+
3
+ import pyqrcode
4
+
5
+ from _base import BaseAuthHandler
6
+ from util import jwt_decode, max_seconds
7
+
8
+
9
+ class DeviceCodeFlow(BaseAuthHandler):
10
+ # noinspection PyTypeChecker
11
+ def __init__(self, auth_server: str, realm: str, client_id: str, client_secret: str):
12
+ super().__init__(auth_server, realm, client_id, client_secret)
13
+
14
+ # Initialize certain properties as Empty
15
+ self._access_token: str = None
16
+ self._access_token_expiry: datetime = None
17
+ self._refresh_token: str = None
18
+ self._refresh_token_expiry: datetime = None
19
+
20
+ self._device_code_endpoint = self._openid_config['device_authorization_endpoint']
21
+
22
+ def _get_user_code(self) -> dict:
23
+ req = self._session.post(
24
+ self._device_code_endpoint,
25
+ data={"client_id": self.client_id, "client_secret": self.client_secret},
26
+ allow_redirects=False
27
+ )
28
+
29
+ # self._device_code = req.json()["device_code"]
30
+ # self._user_code = req.json()["user_code"]
31
+ # self._verification_uri = req.json()["verification_uri"]
32
+ # self._verification_uri_complete = req.json()["verification_uri_complete"]
33
+ # self._expires_in = req.json()["expires_in"]
34
+ # self._poll_interval = req.json()["interval"]
35
+
36
+ return req.json()
37
+
38
+ def authenticate(self) -> dict:
39
+ print("To finish authentication, please scan the QR code (or use the link)")
40
+ print("and the specified device code to complete login on the next screen.\n")
41
+ input("Press Enter to generate the QR code, URL, and device code.")
42
+
43
+ user_code = self._get_user_code()
44
+ qr = pyqrcode.create(user_code["verification_uri_complete"])
45
+ print(qr.terminal(quiet_zone=1))
46
+ print(f"URL: {user_code["verification_uri_complete"]}")
47
+ print(f"Device code: {user_code["device_code"]}\n")
48
+
49
+ print("Waiting for authentication to complete...")
50
+
51
+ for _ in max_seconds(max_seconds=user_code["expires_in"], interval=user_code["interval"]):
52
+ token_request = self._session.post(
53
+ self._token_endpoint,
54
+ data={"device_code": user_code["device_code"],
55
+ "client_id": self.client_id,
56
+ "client_secret": self.client_secret,
57
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code"},
58
+ allow_redirects=False)
59
+
60
+ if 'error' in token_request.keys():
61
+ continue
62
+ elif 'access_token' in token_request.keys():
63
+ # Store current access token and expiry in object
64
+ self._access_token = token_request.json()['access_token']
65
+ self._access_token_expiry = datetime.fromtimestamp(
66
+ int(jwt_decode(self._access_token)['exp']), tz=timezone.utc
67
+ )
68
+
69
+ # Store current refresh token and expiry in object
70
+ self._refresh_token = token_request.json()['refresh_token']
71
+ self._refresh_token_expiry = datetime.fromtimestamp(
72
+ int(jwt_decode(self._refresh_token)['exp']), tz=timezone.utc
73
+ )
74
+ return token_request.json()
75
+ else:
76
+ raise RuntimeError("Unable to authenticate, unknown error.")
77
+
78
+ raise RuntimeError("Device login timed out, restart auth process.")
@@ -0,0 +1,69 @@
1
+ import base64
2
+ import time
3
+ from datetime import datetime, timezone
4
+ import hashlib
5
+ import json
6
+ import secrets
7
+
8
+ from string import ascii_letters, digits
9
+
10
+
11
+ def generate_random_string(length: int = 32) -> str:
12
+ """
13
+ Helper function used to generate random cryptographically-safe strings
14
+ :param length: (int) length of string to generate, defaults to 32
15
+ :return: random string of letters and numbers of specified length.
16
+ """
17
+ return "".join(secrets.choice(ascii_letters + digits) for _ in range(length))
18
+
19
+
20
+ def generate_pkce(length: int = 64) -> dict[str, str]:
21
+ """
22
+ Helper function that can generate PKCE parameters.
23
+ :param length:
24
+ :return:
25
+ """
26
+ verifier = generate_random_string(length)
27
+ challenge = base64.urlsafe_b64encode(
28
+ hashlib.sha256(
29
+ verifier.encode('utf-8')
30
+ ).digest()).decode('utf-8').replace('=', '')
31
+ return {
32
+ 'verifier': verifier,
33
+ 'challenge': challenge
34
+ }
35
+
36
+
37
+ def jwt_decode(jwt: str) -> dict:
38
+ _, payload, _ = jwt.split('.')
39
+ data = payload + "=" * (4 - len(jwt) % 4)
40
+ decoded = base64.b64decode(data).decode('utf-8')
41
+ return json.loads(decoded)
42
+
43
+
44
+ def token_is_valid(token: str) -> tuple[bool, str | None]:
45
+ # noinspection PyBroadException
46
+ try:
47
+ jwt = jwt_decode(token)
48
+ except Exception:
49
+ return False, "Token could not be decoded"
50
+ expiry = datetime.fromtimestamp(int(jwt['exp']), tz=timezone.utc)
51
+ if expiry < datetime.now(tz=timezone.utc):
52
+ return False, "Expired"
53
+
54
+ return True, "Presumed valid, but can only be confirmed against the auth server."
55
+
56
+
57
+ def max_seconds(max_seconds: int, interval: int = 5):
58
+ start_time = time.time()
59
+ end_time = start_time + max_seconds
60
+ yield 0
61
+ while time.time() < end_time:
62
+ if interval > 0:
63
+ next_time = start_time
64
+ while next_time < time.time():
65
+ next_time += interval
66
+ time.sleep(int(round(next_time - time.time())))
67
+ yield int(round(time.time() - start_time))
68
+ if int(round(time.time() + interval)) > int(round(end_time)):
69
+ return
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.4
2
+ Name: keycloak-oauth-system
3
+ Version: 0.1.0a2
4
+ Summary: Keycloak OAuth handler library that uses programmatic evaluation of callback URLs without the need for a callback server
5
+ Author-email: Thomas Ward <teward@thomas-ward.net>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/teward/KeycloakOAuth.git
8
+ Keywords: oauth,oauth 2.0,keycloak
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Programming Language :: Python :: 3.15
17
+ Classifier: Programming Language :: Python :: 3.16
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ License-File: LICENSE
21
+ License-File: AUTHORS
22
+ Requires-Dist: requests
23
+ Requires-Dist: pyqrcode
24
+ Dynamic: license-file
@@ -0,0 +1,14 @@
1
+ AUTHORS
2
+ LICENSE
3
+ pyproject.toml
4
+ keycloak_oauth/__init__.py
5
+ keycloak_oauth/_base.py
6
+ keycloak_oauth/auth_code_flow.py
7
+ keycloak_oauth/client_credentials_flow.py
8
+ keycloak_oauth/device_code_flow.py
9
+ keycloak_oauth/util.py
10
+ keycloak_oauth_system.egg-info/PKG-INFO
11
+ keycloak_oauth_system.egg-info/SOURCES.txt
12
+ keycloak_oauth_system.egg-info/dependency_links.txt
13
+ keycloak_oauth_system.egg-info/requires.txt
14
+ keycloak_oauth_system.egg-info/top_level.txt
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 77.0.3"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "keycloak-oauth-system"
7
+ dynamic = ["version"]
8
+ dependencies = [
9
+ "requests",
10
+ "pyqrcode"
11
+ ]
12
+ requires-python = ">= 3.12"
13
+ authors = [
14
+ {name = "Thomas Ward", email = "teward@thomas-ward.net"},
15
+ ]
16
+ description = "Keycloak OAuth handler library that uses programmatic evaluation of callback URLs without the need for a callback server"
17
+ license = "Apache-2.0"
18
+ license-files = ["LICEN[CS]E*", "AUTHORS"]
19
+ keywords = [
20
+ "oauth",
21
+ "oauth 2.0",
22
+ "keycloak"
23
+ ]
24
+ classifiers = [
25
+ "Development Status :: 3 - Alpha",
26
+ "Intended Audience :: Developers",
27
+ "Operating System :: OS Independent",
28
+ "Programming Language :: Python :: 3 :: Only",
29
+ "Programming Language :: Python :: 3.12",
30
+ "Programming Language :: Python :: 3.13",
31
+ "Programming Language :: Python :: 3.14",
32
+ "Programming Language :: Python :: 3.15",
33
+ "Programming Language :: Python :: 3.16",
34
+ "Typing :: Typed"
35
+ ]
36
+
37
+ [project.urls]
38
+ Repository = "https://github.com/teward/KeycloakOAuth.git"
39
+
40
+ [tool.setuptools.dynamic]
41
+ version = {attr = "keycloak_oauth.__version__"}
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+