|
12 | 12 | from authgate.credstore import default_token_secure_store |
13 | 13 | from authgate.discovery.async_client import AsyncDiscoveryClient |
14 | 14 | from authgate.discovery.client import DiscoveryClient |
15 | | -from authgate.exceptions import AuthFlowError, AuthGateError, NotFoundError |
| 15 | +from authgate.exceptions import AuthFlowError, AuthGateError, NotFoundError, OAuthError |
16 | 16 | from authgate.oauth.async_client import AsyncOAuthClient |
17 | 17 | from authgate.oauth.client import OAuthClient |
18 | 18 | from authgate.oauth.models import Token |
@@ -63,7 +63,7 @@ def authenticate( |
63 | 63 | try: |
64 | 64 | token = ts.token() |
65 | 65 | return client, token |
66 | | - except (NotFoundError, AuthFlowError): |
| 66 | + except (NotFoundError, AuthFlowError, OAuthError): |
67 | 67 | pass |
68 | 68 |
|
69 | 69 | # 5. No valid token — run the appropriate authentication flow |
@@ -111,15 +111,24 @@ async def async_authenticate( |
111 | 111 | # 2. Create async OAuth client |
112 | 112 | client = AsyncOAuthClient(client_id, meta.to_endpoints()) |
113 | 113 |
|
114 | | - # 3. Check stored token |
| 114 | + # 3. Check stored token and attempt refresh if expired |
115 | 115 | store = default_token_secure_store(service_name, store_path) |
116 | 116 | try: |
117 | 117 | stored = store.load(client_id) |
118 | | - if stored.is_valid(): |
119 | | - from authgate.authflow.token_source import _credstore_to_oauth |
| 118 | + from authgate.authflow.token_source import _credstore_to_oauth, _oauth_to_credstore |
120 | 119 |
|
| 120 | + if stored.is_valid(): |
121 | 121 | token = _credstore_to_oauth(stored) |
122 | 122 | return client, token |
| 123 | + |
| 124 | + # Try refreshing with the stored refresh token |
| 125 | + if stored.refresh_token: |
| 126 | + try: |
| 127 | + token = await client.refresh_token(stored.refresh_token) |
| 128 | + store.save(client_id, _oauth_to_credstore(token, client_id)) |
| 129 | + return client, token |
| 130 | + except OAuthError: |
| 131 | + pass |
123 | 132 | except NotFoundError: |
124 | 133 | pass |
125 | 134 |
|
|
0 commit comments