py-oidc-auth-client 2602.0.0__py3-none-any.whl
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.
- py_oidc_auth_client/__init__.py +323 -0
- py_oidc_auth_client/__main__.py +198 -0
- py_oidc_auth_client/exceptions.py +64 -0
- py_oidc_auth_client/flows.py +956 -0
- py_oidc_auth_client/schema.py +105 -0
- py_oidc_auth_client/token_store.py +353 -0
- py_oidc_auth_client/utils.py +279 -0
- py_oidc_auth_client-2602.0.0.dist-info/METADATA +213 -0
- py_oidc_auth_client-2602.0.0.dist-info/RECORD +12 -0
- py_oidc_auth_client-2602.0.0.dist-info/WHEEL +4 -0
- py_oidc_auth_client-2602.0.0.dist-info/entry_points.txt +3 -0
- py_oidc_auth_client-2602.0.0.dist-info/licenses/LICENSE +28 -0
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""
|
|
2
|
+
py_oidc_auth_client
|
|
3
|
+
===================
|
|
4
|
+
|
|
5
|
+
A lightweight OIDC/OAuth 2.0 client library for authenticating against
|
|
6
|
+
servers that use ``py-oidc-auth`` (or any standard OIDC provider).
|
|
7
|
+
|
|
8
|
+
The main entry point is the :func:`authenticate` function which handles
|
|
9
|
+
token caching, refresh, and interactive login automatically.
|
|
10
|
+
|
|
11
|
+
Quick start
|
|
12
|
+
~~~~~~~~~~~
|
|
13
|
+
|
|
14
|
+
.. code-block:: python
|
|
15
|
+
|
|
16
|
+
from py_oidc_auth_client import authenticate
|
|
17
|
+
|
|
18
|
+
# Interactive login (opens browser, returns token)
|
|
19
|
+
token = authenticate(host="https://myapp.example.com")
|
|
20
|
+
print(token["access_token"][:20], "...")
|
|
21
|
+
|
|
22
|
+
# Use the token with any HTTP client
|
|
23
|
+
import httpx
|
|
24
|
+
resp = httpx.get(
|
|
25
|
+
"https://myapp.example.com/api/data",
|
|
26
|
+
headers=token["headers"],
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
Non interactive / batch mode
|
|
30
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
31
|
+
|
|
32
|
+
.. code-block:: python
|
|
33
|
+
|
|
34
|
+
# On your workstation: login once and save the token
|
|
35
|
+
token = authenticate(host="https://myapp.example.com")
|
|
36
|
+
|
|
37
|
+
# On the cluster or in CI: reuses cached token automatically
|
|
38
|
+
token = authenticate(host="https://myapp.example.com")
|
|
39
|
+
|
|
40
|
+
Multiple servers
|
|
41
|
+
~~~~~~~~~~~~~~~~
|
|
42
|
+
|
|
43
|
+
Tokens are cached per host, so authenticating to different servers
|
|
44
|
+
does not overwrite previous tokens:
|
|
45
|
+
|
|
46
|
+
.. code-block:: python
|
|
47
|
+
|
|
48
|
+
token_a = authenticate(host="https://server-a.example.com")
|
|
49
|
+
token_b = authenticate(host="https://server-b.example.com")
|
|
50
|
+
|
|
51
|
+
For finer control over individual flows, see :class:`~flows.DeviceFlow`
|
|
52
|
+
and :class:`~flows.CodeFlow`.
|
|
53
|
+
|
|
54
|
+
CLI usage
|
|
55
|
+
~~~~~~~~~
|
|
56
|
+
|
|
57
|
+
.. code-block:: bash
|
|
58
|
+
|
|
59
|
+
python -m py_oidc_auth_client https://myapp.example.com
|
|
60
|
+
python -m py_oidc_auth_client https://myapp.example.com --timeout 120
|
|
61
|
+
python -m py_oidc_auth_client --list
|
|
62
|
+
python -m py_oidc_auth_client --clear
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
from __future__ import annotations
|
|
66
|
+
|
|
67
|
+
import asyncio
|
|
68
|
+
from typing import List, Optional
|
|
69
|
+
|
|
70
|
+
from .exceptions import AuthError
|
|
71
|
+
from .flows import BaseFlow, CodeFlow, DeviceFlow
|
|
72
|
+
from .schema import DeviceCode, Token
|
|
73
|
+
from .token_store import TokenStore
|
|
74
|
+
|
|
75
|
+
__version__ = "2602.0.0"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def authenticate(
|
|
79
|
+
host: str,
|
|
80
|
+
*,
|
|
81
|
+
login_route: str = "/auth/v2/login",
|
|
82
|
+
token_route: str = "/auth/v2/token",
|
|
83
|
+
device_route: str = "/auth/v2/device",
|
|
84
|
+
redirect_ports: Optional[List[int]] = None,
|
|
85
|
+
store: Optional[TokenStore] = None,
|
|
86
|
+
app_name: str = "py-oidc-auth",
|
|
87
|
+
force: bool = False,
|
|
88
|
+
timeout: Optional[int] = 30,
|
|
89
|
+
) -> Token:
|
|
90
|
+
"""Authenticate to an OIDC protected server and return a token.
|
|
91
|
+
|
|
92
|
+
This is the primary entry point for the library. It handles the
|
|
93
|
+
full authentication lifecycle:
|
|
94
|
+
|
|
95
|
+
1. Check the token store for a cached token for this host.
|
|
96
|
+
2. If the access token is still valid, return it immediately.
|
|
97
|
+
3. If only the refresh token is valid, perform a token refresh.
|
|
98
|
+
4. Otherwise, start an interactive login. The device flow is
|
|
99
|
+
attempted first; if the server does not support it, the
|
|
100
|
+
authorization code flow (local browser) is used as a fallback.
|
|
101
|
+
|
|
102
|
+
Tokens are stored per host in a shared JSON file, so
|
|
103
|
+
authenticating to multiple servers does not overwrite previous
|
|
104
|
+
tokens.
|
|
105
|
+
|
|
106
|
+
Parameters
|
|
107
|
+
----------
|
|
108
|
+
host : str
|
|
109
|
+
Base URL of the application server
|
|
110
|
+
(e.g. ``"https://myapp.example.com"``).
|
|
111
|
+
login_route : str
|
|
112
|
+
Server side route for the authorization code login endpoint.
|
|
113
|
+
token_route : str
|
|
114
|
+
Server side route for the token exchange endpoint.
|
|
115
|
+
device_route : str
|
|
116
|
+
Server side route for the device authorization endpoint.
|
|
117
|
+
redirect_ports : list of int, optional
|
|
118
|
+
Ports to try when starting a local HTTP server for the
|
|
119
|
+
authorization code callback. The first available port is used.
|
|
120
|
+
Defaults to ``[53100, 53101, 53102, 53103, 53104, 53105]``.
|
|
121
|
+
store : TokenStore or None
|
|
122
|
+
Custom :class:`TokenStore` for token persistence. When
|
|
123
|
+
``None`` a default store is created in the platform cache
|
|
124
|
+
directory (e.g. ``~/.cache/<app_name>/token-store.json``).
|
|
125
|
+
app_name : str
|
|
126
|
+
Application name for the cache directory. Only used when
|
|
127
|
+
*store* is ``None``. Defaults to ``"py-oidc-auth"``.
|
|
128
|
+
force : bool
|
|
129
|
+
When ``True``, skip the cache and force a fresh interactive
|
|
130
|
+
login even if a valid token exists.
|
|
131
|
+
timeout : int or None
|
|
132
|
+
Maximum seconds to wait for the user to complete the browser
|
|
133
|
+
login. ``None`` waits indefinitely.
|
|
134
|
+
|
|
135
|
+
Returns
|
|
136
|
+
-------
|
|
137
|
+
Token
|
|
138
|
+
A token dictionary with keys ``access_token``,
|
|
139
|
+
``refresh_token``, ``expires``, ``refresh_expires``,
|
|
140
|
+
``scope``, ``token_type``, and ``headers``.
|
|
141
|
+
|
|
142
|
+
The ``headers`` value is a ready to use dict:
|
|
143
|
+
``{"Authorization": "Bearer eyJ..."}``.
|
|
144
|
+
|
|
145
|
+
Raises
|
|
146
|
+
------
|
|
147
|
+
AuthError
|
|
148
|
+
If authentication fails (timeout, user denial, server error,
|
|
149
|
+
or no interactive session available in a batch environment).
|
|
150
|
+
|
|
151
|
+
Examples
|
|
152
|
+
--------
|
|
153
|
+
Basic interactive login:
|
|
154
|
+
|
|
155
|
+
.. code-block:: python
|
|
156
|
+
|
|
157
|
+
from py_oidc_auth_client import authenticate
|
|
158
|
+
|
|
159
|
+
token = authenticate(host="https://myapp.example.com")
|
|
160
|
+
print(token["access_token"][:20])
|
|
161
|
+
|
|
162
|
+
Authenticate to multiple servers:
|
|
163
|
+
|
|
164
|
+
.. code-block:: python
|
|
165
|
+
|
|
166
|
+
token_a = authenticate(host="https://server-a.example.com")
|
|
167
|
+
token_b = authenticate(host="https://server-b.example.com")
|
|
168
|
+
# Both tokens are cached independently
|
|
169
|
+
|
|
170
|
+
Force re authentication:
|
|
171
|
+
|
|
172
|
+
.. code-block:: python
|
|
173
|
+
|
|
174
|
+
token = authenticate(
|
|
175
|
+
host="https://myapp.example.com",
|
|
176
|
+
force=True,
|
|
177
|
+
timeout=120,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
Custom app name (changes cache directory):
|
|
181
|
+
|
|
182
|
+
.. code-block:: python
|
|
183
|
+
|
|
184
|
+
token = authenticate(
|
|
185
|
+
host="https://myapp.example.com",
|
|
186
|
+
app_name="my-project",
|
|
187
|
+
)
|
|
188
|
+
# Tokens stored in ~/.cache/my-project/token-store.json
|
|
189
|
+
|
|
190
|
+
Custom token store:
|
|
191
|
+
|
|
192
|
+
.. code-block:: python
|
|
193
|
+
|
|
194
|
+
from py_oidc_auth_client import TokenStore, authenticate
|
|
195
|
+
|
|
196
|
+
store = TokenStore("~/.config/myapp/tokens.json")
|
|
197
|
+
token = authenticate(
|
|
198
|
+
host="https://myapp.example.com",
|
|
199
|
+
store=store,
|
|
200
|
+
)
|
|
201
|
+
"""
|
|
202
|
+
return asyncio.run(
|
|
203
|
+
authenticate_async(
|
|
204
|
+
host,
|
|
205
|
+
store=store,
|
|
206
|
+
login_route=login_route,
|
|
207
|
+
device_route=device_route,
|
|
208
|
+
token_route=token_route,
|
|
209
|
+
redirect_ports=redirect_ports,
|
|
210
|
+
app_name=app_name,
|
|
211
|
+
force=force,
|
|
212
|
+
timeout=timeout,
|
|
213
|
+
)
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
async def authenticate_async(
|
|
218
|
+
host: str,
|
|
219
|
+
*,
|
|
220
|
+
login_route: str = "/auth/v2/login",
|
|
221
|
+
token_route: str = "/auth/v2/token",
|
|
222
|
+
device_route: str = "/auth/v2/device",
|
|
223
|
+
redirect_ports: Optional[List[int]] = None,
|
|
224
|
+
store: Optional[TokenStore] = None,
|
|
225
|
+
app_name: str = "py-oidc-auth",
|
|
226
|
+
force: bool = False,
|
|
227
|
+
timeout: Optional[int] = 30,
|
|
228
|
+
) -> Token:
|
|
229
|
+
"""Async version of :func:`authenticate`.
|
|
230
|
+
|
|
231
|
+
Identical behaviour but can be awaited from an existing
|
|
232
|
+
event loop (e.g. inside a Jupyter notebook or an async
|
|
233
|
+
application).
|
|
234
|
+
|
|
235
|
+
Parameters
|
|
236
|
+
----------
|
|
237
|
+
host : str
|
|
238
|
+
Base URL of the application server.
|
|
239
|
+
login_route : str
|
|
240
|
+
Server side route for the authorization code login endpoint.
|
|
241
|
+
token_route : str
|
|
242
|
+
Server side route for the token exchange endpoint.
|
|
243
|
+
device_route : str
|
|
244
|
+
Server side route for the device authorization endpoint.
|
|
245
|
+
redirect_ports : list of int, optional
|
|
246
|
+
Ports to try when starting a local HTTP server for the
|
|
247
|
+
authorization code callback. The first available port is used.
|
|
248
|
+
Defaults to ``[53100, 53101, 53102, 53103, 53104, 53105]``.
|
|
249
|
+
store : TokenStore or None
|
|
250
|
+
Custom token store. Shared default when ``None``.
|
|
251
|
+
app_name : str
|
|
252
|
+
Application name for the cache directory.
|
|
253
|
+
force : bool
|
|
254
|
+
Skip the cache and force a fresh login.
|
|
255
|
+
timeout : int or None
|
|
256
|
+
Maximum seconds to wait for user approval.
|
|
257
|
+
|
|
258
|
+
Returns
|
|
259
|
+
-------
|
|
260
|
+
Token
|
|
261
|
+
The authentication token.
|
|
262
|
+
|
|
263
|
+
Raises
|
|
264
|
+
------
|
|
265
|
+
AuthError
|
|
266
|
+
If authentication fails.
|
|
267
|
+
|
|
268
|
+
Examples
|
|
269
|
+
--------
|
|
270
|
+
.. code-block:: python
|
|
271
|
+
|
|
272
|
+
from py_oidc_auth_client import authenticate_async
|
|
273
|
+
|
|
274
|
+
token = await authenticate_async(
|
|
275
|
+
host="https://myapp.example.com",
|
|
276
|
+
timeout=120,
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
See Also
|
|
280
|
+
--------
|
|
281
|
+
authenticate : Synchronous wrapper for non async code.
|
|
282
|
+
"""
|
|
283
|
+
effective_store = store or TokenStore(app_name=app_name)
|
|
284
|
+
# Try device flow first (works headless and interactively)
|
|
285
|
+
device = DeviceFlow(
|
|
286
|
+
host,
|
|
287
|
+
redirect_ports=redirect_ports,
|
|
288
|
+
login_route=login_route,
|
|
289
|
+
device_route=device_route,
|
|
290
|
+
token_route=token_route,
|
|
291
|
+
store=effective_store,
|
|
292
|
+
timeout=timeout,
|
|
293
|
+
)
|
|
294
|
+
try:
|
|
295
|
+
return await device.authenticate(force=force)
|
|
296
|
+
except AuthError as device_error:
|
|
297
|
+
if device_error.status_code == 503:
|
|
298
|
+
# Server does not support device flow, fall back to code flow
|
|
299
|
+
code = CodeFlow(
|
|
300
|
+
host,
|
|
301
|
+
redirect_ports=redirect_ports,
|
|
302
|
+
login_route=login_route,
|
|
303
|
+
device_route=device_route,
|
|
304
|
+
token_route=token_route,
|
|
305
|
+
store=effective_store,
|
|
306
|
+
timeout=timeout,
|
|
307
|
+
)
|
|
308
|
+
return await code.authenticate(force=force)
|
|
309
|
+
raise
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
__all__ = [
|
|
313
|
+
"AuthError",
|
|
314
|
+
"BaseFlow",
|
|
315
|
+
"CodeFlow",
|
|
316
|
+
"DeviceCode",
|
|
317
|
+
"DeviceFlow",
|
|
318
|
+
"Token",
|
|
319
|
+
"TokenStore",
|
|
320
|
+
"authenticate",
|
|
321
|
+
"authenticate_async",
|
|
322
|
+
"__version__",
|
|
323
|
+
]
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CLI entry point for py_oidc_auth_client.
|
|
3
|
+
|
|
4
|
+
Usage::
|
|
5
|
+
|
|
6
|
+
python -m py_oidc_auth_client https://myapp.example.com
|
|
7
|
+
python -m py_oidc_auth_client https://myapp.example.com --timeout 120
|
|
8
|
+
python -m py_oidc_auth_client https://myapp.example.com --force
|
|
9
|
+
python -m py_oidc_auth_client --list
|
|
10
|
+
python -m py_oidc_auth_client --clear
|
|
11
|
+
python -m py_oidc_auth_client --remove https://myapp.example.com
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import sys
|
|
19
|
+
from typing import Optional, Sequence
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
from rich_argparse import (
|
|
23
|
+
ArgumentDefaultsRichHelpFormatter as ArgumentFormatter,
|
|
24
|
+
)
|
|
25
|
+
except ImportError:
|
|
26
|
+
from argparse import ArgumentDefaultsHelpFormatter as ArgumentFormatter
|
|
27
|
+
|
|
28
|
+
from . import TokenStore, authenticate
|
|
29
|
+
from .exceptions import AuthError
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _build_parser(prog: str) -> argparse.ArgumentParser:
|
|
33
|
+
parser = argparse.ArgumentParser(
|
|
34
|
+
prog=prog,
|
|
35
|
+
description="Authenticate to an OIDC protected server.",
|
|
36
|
+
formatter_class=ArgumentFormatter,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
# Positional: host (optional so that --list/--clear work without it)
|
|
40
|
+
parser.add_argument(
|
|
41
|
+
"host",
|
|
42
|
+
nargs="?",
|
|
43
|
+
default=None,
|
|
44
|
+
help="Base URL of the server (e.g. https://myapp.example.com).",
|
|
45
|
+
)
|
|
46
|
+
parser.add_argument(
|
|
47
|
+
"-l",
|
|
48
|
+
"--login-route",
|
|
49
|
+
help="Server path for the authorization code login endpoint.",
|
|
50
|
+
default="/auth/v2/login",
|
|
51
|
+
)
|
|
52
|
+
parser.add_argument(
|
|
53
|
+
"-t",
|
|
54
|
+
"--token-route",
|
|
55
|
+
help="Server path for the token exchange endpoint.",
|
|
56
|
+
default="/auth/v2/token",
|
|
57
|
+
)
|
|
58
|
+
parser.add_argument(
|
|
59
|
+
"-d",
|
|
60
|
+
"--device-route",
|
|
61
|
+
help="Server path for the device authorization endpoint.",
|
|
62
|
+
default="/auth/v2/device",
|
|
63
|
+
)
|
|
64
|
+
parser.add_argument(
|
|
65
|
+
"-p",
|
|
66
|
+
"--ports",
|
|
67
|
+
help="Ports to try for the local callback server (code flow only).",
|
|
68
|
+
default=[53100, 53101, 53102, 53103, 53104, 53105],
|
|
69
|
+
nargs="+",
|
|
70
|
+
)
|
|
71
|
+
# Auth options
|
|
72
|
+
parser.add_argument(
|
|
73
|
+
"--force",
|
|
74
|
+
action="store_true",
|
|
75
|
+
help="Force a fresh login even if a cached token exists.",
|
|
76
|
+
)
|
|
77
|
+
parser.add_argument(
|
|
78
|
+
"--timeout",
|
|
79
|
+
type=int,
|
|
80
|
+
default=30,
|
|
81
|
+
help="Seconds to wait for the user to approve (default: 30).",
|
|
82
|
+
)
|
|
83
|
+
parser.add_argument(
|
|
84
|
+
"--app-name",
|
|
85
|
+
default="py-oidc-auth",
|
|
86
|
+
help=(
|
|
87
|
+
"Application name for the cache directory " "(default: py-oidc-auth)."
|
|
88
|
+
),
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
# Store management
|
|
92
|
+
store_group = parser.add_argument_group("token store management")
|
|
93
|
+
store_group.add_argument(
|
|
94
|
+
"--list",
|
|
95
|
+
action="store_true",
|
|
96
|
+
dest="list_hosts",
|
|
97
|
+
help="List all hosts with cached tokens, then exit.",
|
|
98
|
+
)
|
|
99
|
+
store_group.add_argument(
|
|
100
|
+
"--clear",
|
|
101
|
+
action="store_true",
|
|
102
|
+
help="Remove all cached tokens, then exit.",
|
|
103
|
+
)
|
|
104
|
+
store_group.add_argument(
|
|
105
|
+
"--remove",
|
|
106
|
+
metavar="HOST",
|
|
107
|
+
help="Remove the cached token for HOST, then exit.",
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
# Output options
|
|
111
|
+
parser.add_argument(
|
|
112
|
+
"--json",
|
|
113
|
+
action="store_true",
|
|
114
|
+
dest="output_json",
|
|
115
|
+
help="Print the full token as JSON instead of a summary.",
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
return parser
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def main(argv: Optional[Sequence[str]] = None, prog: str = "oidc-auth") -> int:
|
|
122
|
+
"""Run the CLI.
|
|
123
|
+
|
|
124
|
+
Parameters
|
|
125
|
+
----------
|
|
126
|
+
argv : list of str or None
|
|
127
|
+
Command line arguments. Uses ``sys.argv[1:]`` when ``None``.
|
|
128
|
+
prog: str
|
|
129
|
+
Name of the cli
|
|
130
|
+
|
|
131
|
+
Returns
|
|
132
|
+
-------
|
|
133
|
+
int
|
|
134
|
+
Exit code (0 on success, 1 on error).
|
|
135
|
+
"""
|
|
136
|
+
parser = _build_parser(prog)
|
|
137
|
+
args = parser.parse_args(argv)
|
|
138
|
+
|
|
139
|
+
store = TokenStore(app_name=args.app_name)
|
|
140
|
+
|
|
141
|
+
# -- Store management commands (no host required) -------------------
|
|
142
|
+
|
|
143
|
+
if args.list_hosts:
|
|
144
|
+
hosts = store.hosts()
|
|
145
|
+
if not hosts:
|
|
146
|
+
print("No cached tokens.")
|
|
147
|
+
else:
|
|
148
|
+
for host in sorted(hosts):
|
|
149
|
+
token = store.get(host)
|
|
150
|
+
status = "valid" if token else "expired"
|
|
151
|
+
print(f" {host} ({status})")
|
|
152
|
+
return 0
|
|
153
|
+
|
|
154
|
+
if args.clear:
|
|
155
|
+
store.clear()
|
|
156
|
+
print("All cached tokens removed.")
|
|
157
|
+
return 0
|
|
158
|
+
|
|
159
|
+
if args.remove:
|
|
160
|
+
if store.remove(args.remove):
|
|
161
|
+
print(f"Removed token for {args.remove}")
|
|
162
|
+
else:
|
|
163
|
+
print(f"No cached token for {args.remove}")
|
|
164
|
+
return 0
|
|
165
|
+
|
|
166
|
+
# -- Authentication (host required) ---------------------------------
|
|
167
|
+
|
|
168
|
+
if not args.host:
|
|
169
|
+
parser.error("host is required for authentication")
|
|
170
|
+
|
|
171
|
+
try:
|
|
172
|
+
token = authenticate(
|
|
173
|
+
args.host,
|
|
174
|
+
store=store,
|
|
175
|
+
app_name=args.app_name,
|
|
176
|
+
force=args.force,
|
|
177
|
+
timeout=args.timeout,
|
|
178
|
+
)
|
|
179
|
+
except AuthError as exc:
|
|
180
|
+
print(f"Authentication failed: {exc}", file=sys.stderr)
|
|
181
|
+
return 1
|
|
182
|
+
|
|
183
|
+
if args.output_json:
|
|
184
|
+
print(json.dumps(dict(token), indent=2))
|
|
185
|
+
else:
|
|
186
|
+
access = token.get("access_token", "")
|
|
187
|
+
preview = f"{access[:20]}..." if len(access) > 20 else access
|
|
188
|
+
print(f"Authenticated to {args.host}")
|
|
189
|
+
print(f" access_token: {preview}")
|
|
190
|
+
print(f" scope: {token.get('scope', '')}")
|
|
191
|
+
|
|
192
|
+
return 0
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
if __name__ == "__main__":
|
|
196
|
+
raise SystemExit(
|
|
197
|
+
main(prog="python -m py_oidc_auth_client")
|
|
198
|
+
) # pragma: no cover
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Exceptions
|
|
3
|
+
==========
|
|
4
|
+
|
|
5
|
+
All exceptions raised by the py_oidc_auth_client library.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Any, Dict, Optional
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AuthError(Exception):
|
|
12
|
+
"""Authentication or token exchange failed.
|
|
13
|
+
|
|
14
|
+
Parameters
|
|
15
|
+
----------
|
|
16
|
+
message : str
|
|
17
|
+
Human readable summary of what went wrong.
|
|
18
|
+
detail : dict, optional
|
|
19
|
+
Raw error payload from the OIDC provider, typically containing
|
|
20
|
+
``"error"`` and ``"error_description"`` keys.
|
|
21
|
+
status_code : int
|
|
22
|
+
HTTP status code from the upstream response. Defaults to 500
|
|
23
|
+
when the error did not originate from an HTTP call.
|
|
24
|
+
|
|
25
|
+
Attributes
|
|
26
|
+
----------
|
|
27
|
+
message : str
|
|
28
|
+
The error summary.
|
|
29
|
+
detail : dict
|
|
30
|
+
Provider error payload (empty dict if not available).
|
|
31
|
+
status_code : int
|
|
32
|
+
HTTP status code.
|
|
33
|
+
|
|
34
|
+
Examples
|
|
35
|
+
--------
|
|
36
|
+
Catching authentication failures:
|
|
37
|
+
|
|
38
|
+
.. code-block:: python
|
|
39
|
+
|
|
40
|
+
from py_oidc_auth_client import authenticate
|
|
41
|
+
from py_oidc_auth_client.exceptions import AuthError
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
token = authenticate(host="https://myapp.example.com")
|
|
45
|
+
except AuthError as exc:
|
|
46
|
+
print(f"Login failed ({exc.status_code}): {exc}")
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
message: str,
|
|
52
|
+
detail: Optional[Dict[str, Any]] = None,
|
|
53
|
+
status_code: int = 500,
|
|
54
|
+
) -> None:
|
|
55
|
+
super().__init__(message)
|
|
56
|
+
self.message = message
|
|
57
|
+
self.detail = detail or {}
|
|
58
|
+
self.status_code = status_code
|
|
59
|
+
|
|
60
|
+
def __str__(self) -> str:
|
|
61
|
+
"""Represent Error class as String."""
|
|
62
|
+
if self.detail:
|
|
63
|
+
return f"{self.message}: {self.detail}"
|
|
64
|
+
return self.message
|