-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver_client.py
More file actions
2584 lines (2177 loc) · 104 KB
/
Copy pathserver_client.py
File metadata and controls
2584 lines (2177 loc) · 104 KB
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Main client for auth0-server-python SDK.
Handles authentication flows, token management, and user sessions.
"""
import asyncio
import json
import time
from collections import OrderedDict
from typing import Any, Callable, Generic, Optional, TypeVar, Union
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
import httpx
import jwt
from authlib.integrations.base_client.errors import OAuthError
from authlib.integrations.httpx_client import AsyncOAuth2Client
from pydantic import ValidationError
from auth0_server_python.auth_server.mfa_client import MfaClient
from auth0_server_python.auth_server.my_account_client import MyAccountClient
from auth0_server_python.auth_types import (
CompleteConnectAccountRequest,
CompleteConnectAccountResponse,
ConnectAccountOptions,
ConnectAccountRequest,
CustomTokenExchangeOptions,
ListConnectedAccountConnectionsResponse,
ListConnectedAccountsResponse,
LoginWithCustomTokenExchangeOptions,
LoginWithCustomTokenExchangeResult,
LogoutOptions,
LogoutTokenClaims,
MfaRequirements,
StartInteractiveLoginOptions,
StateData,
TokenExchangeResponse,
TokenSet,
TransactionData,
UserClaims,
)
from auth0_server_python.error import (
AccessTokenError,
AccessTokenErrorCode,
AccessTokenForConnectionError,
AccessTokenForConnectionErrorCode,
ApiError,
BackchannelLogoutError,
ConfigurationError,
CustomTokenExchangeError,
CustomTokenExchangeErrorCode,
DomainResolverError,
InvalidArgumentError,
IssuerValidationError,
MfaRequiredError,
MissingRequiredArgumentError,
MissingTransactionError,
OrganizationTokenValidationError,
PollingApiError,
StartLinkUserError,
)
from auth0_server_python.telemetry import Telemetry
from auth0_server_python.utils import PKCE, URL, State
from auth0_server_python.utils.helpers import (
build_domain_resolver_context,
validate_org_claims,
validate_resolved_domain_value,
)
# Generic type for store options
TStoreOptions = TypeVar('TStoreOptions')
# redirect_uri is intentionally excluded — in MCD mode it is built
# dynamically from the resolved domain at login time.
INTERNAL_AUTHORIZE_PARAMS = ["client_id", "response_type",
"code_challenge", "code_challenge_method", "state", "nonce", "scope"]
class ServerClient(Generic[TStoreOptions]):
"""
Main client for Auth0 server SDK. Handles authentication flows, session management,
and token operations using Authlib for OIDC functionality.
"""
DEFAULT_AUDIENCE_STATE_KEY = "default"
# ============================================================================
# INITIALIZATION
# ============================================================================
def __init__(
self,
domain: Union[str, Callable[[Optional[dict[str, Any]]], str]] = None,
client_id: str = None,
client_secret: str = None,
redirect_uri: Optional[str] = None,
secret: str = None,
transaction_store=None,
state_store=None,
transaction_identifier: str = "_a0_tx",
state_identifier: str = "_a0_session",
authorization_params: Optional[dict[str, Any]] = None,
pushed_authorization_requests: bool = False,
organization: Optional[str] = None,
):
"""
Initialize the Auth0 server client.
Args:
domain: Auth0 domain - either a static string (e.g., 'tenant.auth0.com') or a callable that resolves domain dynamically.
client_id: Auth0 client ID
client_secret: Auth0 client secret
redirect_uri: Default redirect URI for authentication
secret: Secret used for encryption
transaction_store: Custom transaction store (defaults to MemoryTransactionStore)
state_store: Custom state store (defaults to MemoryStateStore)
transaction_identifier: Identifier for transaction data
state_identifier: Identifier for state data
authorization_params: Default parameters for authorization requests
pushed_authorization_requests: Whether to use Pushed Authorization Requests
organization: Default organization for all login flows from this client.
Can be an org ID (e.g. 'org_abc123') or an org name (e.g. 'acme-corp').
Per-login values passed in StartInteractiveLoginOptions always override this.
"""
if not secret:
raise MissingRequiredArgumentError("secret")
if domain is None:
raise ConfigurationError(
"Domain is required"
)
# Validate domain type
if not isinstance(domain, str) and not callable(domain):
raise ConfigurationError(
f"Domain must be either a string or a callable function. "
f"Got {type(domain).__name__} instead."
)
# Determine if domain is static string or dynamic callable
if callable(domain):
self._domain = None
self._domain_resolver = domain
else:
# Validate static domain string
domain_str = str(domain)
if not domain_str or domain_str.strip() == "":
raise ConfigurationError("Domain cannot be empty.")
self._domain = domain_str
self._domain_resolver = None
self._client_id = client_id
self._client_secret = client_secret
self._redirect_uri = redirect_uri
self._secret = secret
self._default_authorization_params = authorization_params or {}
self._pushed_authorization_requests = pushed_authorization_requests # store the flag
self._organization = organization
# Initialize stores
self._transaction_store = transaction_store
self._state_store = state_store
self._transaction_identifier = transaction_identifier
self._state_identifier = state_identifier
# Initialize telemetry
self._telemetry = Telemetry.default()
self._telemetry_headers = self._telemetry.headers
# Initialize OAuth client
self._oauth = AsyncOAuth2Client(
client_id=client_id,
client_secret=client_secret,
headers=self._telemetry_headers,
)
self._my_account_client = MyAccountClient(
domain=domain, headers=self._telemetry_headers
)
# Unified cache for OIDC metadata and JWKS per domain (LRU eviction + TTL)
self._discovery_cache: OrderedDict[str, dict] = OrderedDict()
self._cache_ttl = 600 # 10 mins. TTL
self._cache_max_entries = 100 # Max 100 domains
# Initialize MFA client
self._mfa_client = MfaClient(
domain=domain,
client_id=self._client_id,
client_secret=self._client_secret,
secret=self._secret,
state_store=self._state_store,
state_identifier=self._state_identifier,
headers=self._telemetry_headers,
)
def _get_http_client(self, **kwargs) -> httpx.AsyncClient:
"""Return an httpx.AsyncClient with telemetry headers injected."""
headers = {**kwargs.pop("headers", {}), **self._telemetry_headers}
return httpx.AsyncClient(headers=headers, **kwargs)
def _normalize_url(self, value: str) -> str:
"""
Normalize a URL-like value (domain or issuer) for comparison.
Ensures https:// scheme, lowercases, and strips trailing slashes.
"""
if not value:
return value
value = value.lower()
if value.startswith('https://'):
pass
elif value.startswith('http://'):
value = value.replace('http://', 'https://')
else:
value = f'https://{value}'
return value.rstrip('/')
async def _resolve_current_domain(self, store_options=None) -> str:
"""Resolve domain from resolver function or return static domain."""
if self._domain_resolver:
context = build_domain_resolver_context(store_options)
try:
resolved = await self._domain_resolver(context)
return validate_resolved_domain_value(resolved)
except DomainResolverError:
raise
except Exception as e:
raise DomainResolverError(
f"Domain resolver function raised an exception: {str(e)}",
original_error=e
)
return self._domain
def _get_session_domain(self, state_data_dict: dict) -> Optional[str]:
"""
Get session domain with 3-tier fallback for backward compatibility.
Legacy sessions created before MCD support may not have a 'domain' field.
Fallback chain matches JS SDK's #getSessionDomain:
1. state_data.domain — new sessions have this
2. self._domain — static domain (if configured)
3. Extract hostname from user.iss — derive from user's issuer claim
"""
domain = state_data_dict.get('domain')
if domain:
return domain
if self._domain:
return self._domain
user = state_data_dict.get('user')
if isinstance(user, dict):
iss = user.get('iss')
else:
iss = getattr(user, 'iss', None) if user else None
if iss:
parsed = urlparse(iss)
return parsed.hostname
return None
async def _verify_and_decode_jwt(
self, token: str, jwks: dict, audience: Optional[str] = None
) -> dict:
"""
Find signing key in JWKS by kid and decode JWT.
Verifies signature but disables built-in issuer validation
(callers perform normalized issuer comparison separately).
Args:
token: The JWT to verify and decode
jwks: The JWKS dict containing signing keys
audience: Optional expected audience claim
Returns:
Decoded claims dictionary
Raises:
ValueError: If no matching key found in JWKS for the token's kid
"""
unverified_header = jwt.get_unverified_header(token)
kid = unverified_header.get("kid")
signing_key = None
for key in jwks.get("keys", []):
if key.get("kid") == kid:
signing_key = jwt.PyJWK.from_dict(key)
break
if not signing_key:
raise ValueError(f"No matching key found in JWKS for kid: {kid}")
decode_options = {"verify_signature": True, "verify_iss": False}
kwargs = {"algorithms": ["RS256"], "options": decode_options}
if audience:
kwargs["audience"] = audience
return jwt.decode(token, signing_key.key, **kwargs)
async def _fetch_oidc_metadata(self, domain: str) -> dict:
"""Fetch OIDC metadata from domain."""
normalized_domain = self._normalize_url(domain)
metadata_url = f"{normalized_domain}/.well-known/openid-configuration"
async with self._get_http_client() as client:
response = await client.get(metadata_url)
response.raise_for_status()
return response.json()
def _purge_expired_cache_entries(self):
"""Purge all expired entries from the discovery cache."""
now = time.time()
expired = [k for k, v in self._discovery_cache.items() if v["expires_at"] <= now]
for k in expired:
del self._discovery_cache[k]
def _ensure_cache_capacity(self):
"""Evict least recently used entry if cache is at capacity."""
if len(self._discovery_cache) >= self._cache_max_entries:
self._discovery_cache.popitem(last=False)
async def _get_oidc_metadata_cached(self, domain: str) -> dict:
"""
Get OIDC metadata with caching (LRU eviction + TTL).
Uses a unified cache shared with JWKS when metadata expires,
the corresponding JWKS is also invalidated.
Args:
domain: Auth0 domain
Returns:
OIDC metadata document
"""
now = time.time()
# Check cache
if domain in self._discovery_cache:
cached = self._discovery_cache[domain]
if cached["expires_at"] > now:
self._discovery_cache.move_to_end(domain)
return cached["metadata"]
# Expired — remove entire entry (metadata + jwks)
del self._discovery_cache[domain]
# Cache miss/expired - fetch fresh
metadata = await self._fetch_oidc_metadata(domain)
# Purge expired entries and ensure capacity
self._purge_expired_cache_entries()
self._ensure_cache_capacity()
# Store in cache with jwks=None (lazily populated when needed)
self._discovery_cache[domain] = {
"metadata": metadata,
"jwks": None,
"expires_at": now + self._cache_ttl
}
return metadata
async def _fetch_jwks(self, jwks_uri: str) -> dict:
"""
Fetch JWKS (JSON Web Key Set) from jwks_uri.
Args:
jwks_uri: The JWKS endpoint URL
Returns:
JWKS document containing public keys
Raises:
ApiError: If JWKS fetch fails
"""
try:
async with self._get_http_client() as client:
response = await client.get(jwks_uri)
response.raise_for_status()
return response.json()
except Exception as e:
raise ApiError("jwks_fetch_error", f"Failed to fetch JWKS from {jwks_uri}", e)
async def _get_jwks_cached(self, domain: str, metadata: dict = None) -> dict:
"""
Get JWKS with caching using OIDC discovery (LRU eviction + TTL).
Uses a unified cache shared with metadata — JWKS is lazily populated
on first access and invalidated when the cache entry expires.
Args:
domain: Auth0 domain
metadata: Optional OIDC metadata (if already fetched)
Returns:
JWKS document
Raises:
ApiError: If JWKS fetch fails or jwks_uri missing from metadata
"""
now = time.time()
# Check cache — entry exists, not expired, and jwks already fetched
if domain in self._discovery_cache:
cached = self._discovery_cache[domain]
if cached["expires_at"] > now:
if cached["jwks"] is not None:
self._discovery_cache.move_to_end(domain)
return cached["jwks"]
# Entry valid but jwks not yet fetched — use cached metadata
metadata = cached["metadata"]
else:
# Expired — remove entire entry
del self._discovery_cache[domain]
# Get metadata if not available from cache or parameter
if not metadata:
metadata = await self._get_oidc_metadata_cached(domain)
jwks_uri = metadata.get('jwks_uri')
if not jwks_uri:
raise ApiError(
"missing_jwks_uri",
f"OIDC metadata for {domain} does not contain jwks_uri. Provider may be non-RFC-compliant."
)
# Fetch JWKS
jwks = await self._fetch_jwks(jwks_uri)
# Update existing cache entry with jwks (entry created by _get_oidc_metadata_cached)
if domain in self._discovery_cache:
self._discovery_cache[domain]["jwks"] = jwks
self._discovery_cache.move_to_end(domain)
else:
# Edge case: entry was evicted between metadata and jwks fetch
self._purge_expired_cache_entries()
self._ensure_cache_capacity()
self._discovery_cache[domain] = {
"metadata": metadata,
"jwks": jwks,
"expires_at": now + self._cache_ttl
}
return jwks
# ============================================================================
# INTERACTIVE LOGIN FLOW
# Handles browser-based authentication using the Authorization Code flow
# with PKCE for secure token exchange.
# ============================================================================
async def start_interactive_login(
self,
options: Optional[StartInteractiveLoginOptions] = None,
store_options: dict = None
) -> str:
"""
Starts the interactive login process and returns a URL to redirect to.
Args:
options: Configuration options for the login process
store_options: Store options containing request/response
Returns:
Authorization URL to redirect the user to
"""
options = options or StartInteractiveLoginOptions()
# Resolve domain (static or dynamic)
origin_domain = await self._resolve_current_domain(store_options)
# Fetch OIDC metadata from resolved domain
try:
metadata = await self._get_oidc_metadata_cached(origin_domain)
except Exception as e:
raise ApiError("metadata_error",
"Failed to fetch OIDC metadata", e)
# Get effective authorization params (merge defaults with provided ones)
auth_params = dict(self._default_authorization_params)
if options.authorization_params:
auth_params.update(
{k: v for k, v in options.authorization_params.items(
) if k not in INTERNAL_AUTHORIZE_PARAMS}
)
# Ensure we have a redirect_uri
if "redirect_uri" not in auth_params and not self._redirect_uri:
raise MissingRequiredArgumentError("redirect_uri")
# Use the default redirect_uri if none is specified
if "redirect_uri" not in auth_params and self._redirect_uri:
auth_params["redirect_uri"] = self._redirect_uri
# Generate PKCE code verifier and challenge
code_verifier = PKCE.generate_code_verifier()
code_challenge = PKCE.generate_code_challenge(code_verifier)
# Add PKCE parameters to the authorization request
auth_params["code_challenge"] = code_challenge
auth_params["code_challenge_method"] = "S256"
# State parameter to prevent CSRF
state = PKCE.generate_random_string(32)
auth_params["state"] = state
# Merge any requested scope with defaults
requested_scope = options.authorization_params.get("scope", None) if options.authorization_params else None
audience = auth_params.get("audience", None)
merged_scope = self._merge_scope_with_defaults(requested_scope, audience)
auth_params["scope"] = merged_scope
# Typed org/invitation fields win over anything already in auth_params from authorization_params.
resolved_org = options.organization or self._organization
if resolved_org and not resolved_org.strip():
raise InvalidArgumentError("organization", "organization must not be blank")
if resolved_org:
auth_params["organization"] = resolved_org
if options.invitation:
auth_params["invitation"] = options.invitation
# Build the transaction data to store with domain
transaction_data = TransactionData(
code_verifier=code_verifier,
app_state=options.app_state,
audience=audience,
domain=origin_domain,
redirect_uri=auth_params.get("redirect_uri"),
organization=resolved_org,
)
# Store the transaction data
await self._transaction_store.set(
f"{self._transaction_identifier}:{state}",
transaction_data,
options=store_options
)
# Set metadata for OAuth client
self._oauth.metadata = metadata
# If PAR is enabled, use the PAR endpoint
if self._pushed_authorization_requests:
par_endpoint = self._oauth.metadata.get(
"pushed_authorization_request_endpoint")
if not par_endpoint:
raise ApiError(
"configuration_error", "PAR is enabled but pushed_authorization_request_endpoint is missing in metadata")
auth_params["client_id"] = self._client_id
# Post the auth_params to the PAR endpoint
async with self._get_http_client() as client:
par_response = await client.post(
par_endpoint,
data=auth_params,
auth=(self._client_id, self._client_secret)
)
if par_response.status_code not in (200, 201):
error_data = par_response.json()
raise ApiError(
error_data.get("error", "par_error"),
error_data.get(
"error_description", "Failed to obtain request_uri from PAR endpoint")
)
par_data = par_response.json()
request_uri = par_data.get("request_uri")
if not request_uri:
raise ApiError(
"par_error", "No request_uri returned from PAR endpoint")
auth_endpoint = self._oauth.metadata.get("authorization_endpoint")
final_url = f"{auth_endpoint}?request_uri={request_uri}&response_type={auth_params['response_type']}&client_id={self._client_id}"
return final_url
else:
if "authorization_endpoint" not in self._oauth.metadata:
raise ApiError("configuration_error",
"Authorization endpoint missing in OIDC metadata")
authorization_endpoint = self._oauth.metadata["authorization_endpoint"]
try:
auth_url, state = self._oauth.create_authorization_url(
authorization_endpoint, **auth_params)
except Exception as e:
raise ApiError("authorization_url_error",
"Failed to create authorization URL", e)
return auth_url
async def complete_interactive_login(
self,
url: str,
store_options: dict = None
) -> dict[str, Any]:
"""
Completes the login process after user is redirected back.
Args:
url: The full callback URL including query parameters
store_options: Options to pass to the state store
Returns:
Dictionary containing session data and app state
"""
# Parse the URL to get query parameters
parsed_url = urlparse(url)
query_params = parse_qs(parsed_url.query)
# Get state parameter from the URL
state = query_params.get("state", [""])[0]
if not state:
raise MissingRequiredArgumentError("state")
# Retrieve the transaction data using the state
transaction_identifier = f"{self._transaction_identifier}:{state}"
transaction_data = await self._transaction_store.get(transaction_identifier, options=store_options)
if not transaction_data:
raise MissingTransactionError()
# Check for error response from Auth0
if "error" in query_params:
error = query_params.get("error", [""])[0]
error_description = query_params.get("error_description", [""])[0]
raise ApiError(error, error_description)
# Get the authorization code from the URL
code = query_params.get("code", [""])[0]
if not code:
raise MissingRequiredArgumentError("code")
# Get domain from transaction, or resolve domain if not present (resolver mode)
origin_domain = transaction_data.domain or await self._resolve_current_domain(store_options)
# Fetch metadata and derive issuer from the origin domain
metadata = await self._get_oidc_metadata_cached(origin_domain)
origin_issuer = metadata.get('issuer')
self._oauth.metadata = metadata
# Exchange the code for tokens
# Use redirect_uri from transaction if available, otherwise fall back to default
token_redirect_uri = transaction_data.redirect_uri or self._redirect_uri
try:
token_endpoint = self._oauth.metadata["token_endpoint"]
token_response = await self._oauth.fetch_token(
token_endpoint,
code=code,
code_verifier=transaction_data.code_verifier,
redirect_uri=token_redirect_uri,
)
except OAuthError as e:
# Raise a custom error (or handle it as appropriate)
raise ApiError(
"token_error", f"Token exchange failed: {str(e)}", e)
# Use the userinfo field from the token_response for user claims
user_info = token_response.get("userinfo")
user_claims = None
id_token = token_response.get("id_token")
expected_org = transaction_data.organization
if not user_info and not id_token and expected_org:
raise OrganizationTokenValidationError(
"Organization was requested but the token response included neither an ID token nor userinfo; "
"cannot verify organization membership"
)
if user_info:
if not isinstance(user_info, dict):
if expected_org:
raise OrganizationTokenValidationError(
"Userinfo response is not a valid claims dictionary; cannot verify organization membership"
)
raise ApiError(
"invalid_response",
"Userinfo response is not a valid claims dictionary"
)
if expected_org:
validate_org_claims(user_info, expected_org)
user_claims = UserClaims.parse_obj(user_info)
elif id_token:
# Fetch JWKS for signature verification
jwks = await self._get_jwks_cached(origin_domain, metadata)
# Decode and verify ID token with signature verification enabled
try:
claims = await self._verify_and_decode_jwt(
id_token, jwks, audience=self._client_id
)
# Custom normalized issuer validation
token_issuer = claims.get("iss", "")
if self._normalize_url(token_issuer) != self._normalize_url(origin_issuer):
raise IssuerValidationError("ID token issuer mismatch. Ensure your Auth0 domain is configured correctly.")
# Organization claim validation — mandatory when org was requested.
if expected_org:
validate_org_claims(claims, expected_org)
user_claims = UserClaims.parse_obj(claims)
except ValueError as e:
raise ApiError("jwks_key_not_found", str(e))
except jwt.InvalidSignatureError as e:
raise ApiError(
"invalid_signature",
f"ID token signature verification failed. The token may have been tampered with or is from an untrusted source: {str(e)}",
e
)
except jwt.InvalidAudienceError as e:
raise ApiError(
"invalid_audience",
f"ID token audience mismatch. Expected: {self._client_id}. Ensure your client_id is configured correctly: {str(e)}",
e
)
except jwt.ExpiredSignatureError as e:
raise ApiError(
"token_expired",
f"ID token has expired: {str(e)}",
e
)
except jwt.InvalidTokenError as e:
raise ApiError(
"invalid_token",
f"ID token verification failed: {str(e)}",
e
)
# Build a token set using the token response data
token_set = TokenSet(
audience=transaction_data.audience or self.DEFAULT_AUDIENCE_STATE_KEY,
access_token=token_response.get("access_token", ""),
scope=token_response.get("scope", ""),
expires_at=int(time.time()) +
token_response.get("expires_in", 3600)
)
# Generate a session id (sid) from token_response or transaction data, or create a new one
sid = user_info.get(
"sid") if user_info and "sid" in user_info else PKCE.generate_random_string(32)
# Construct state data to represent the session
state_data = StateData(
user=user_claims,
id_token=token_response.get("id_token"),
# might be None if not provided
refresh_token=token_response.get("refresh_token"),
token_sets=[token_set],
domain=origin_domain,
internal={
"sid": sid,
"created_at": int(time.time())
}
)
# Store the state data in the state store using store_options (Response required)
await self._state_store.set(self._state_identifier, state_data, options=store_options)
# Clean up transaction data after successful login
await self._transaction_store.delete(transaction_identifier, options=store_options)
result = {"state_data": state_data.dict()}
if transaction_data.app_state:
result["app_state"] = transaction_data.app_state
# For RAR
authorization_details = token_response.get("authorization_details")
if authorization_details:
result["authorization_details"] = authorization_details
return result
# ============================================================================
# USER SESSION MANAGEMENT
# Methods for retrieving user information, session data, and logout operations.
# ============================================================================
async def get_user(self, store_options: Optional[dict[str, Any]] = None) -> Optional[dict[str, Any]]:
"""
Retrieves the user from the store, or None if no user found.
Args:
store_options: Optional options used to pass to the Transaction and State Store.
Returns:
The user, or None if no user found in the store.
"""
state_data = await self._state_store.get(self._state_identifier, store_options)
if state_data:
# Domain check should work for both Pydantic models and plain dicts
if hasattr(state_data, "dict") and callable(state_data.dict):
state_data = state_data.dict()
# In resolver mode, reject sessions with mismatched domain
if self._domain_resolver:
session_domain = self._get_session_domain(state_data)
if not session_domain:
return None
current_domain = await self._resolve_current_domain(store_options)
if self._normalize_url(session_domain) != self._normalize_url(current_domain):
return None
return state_data.get("user")
return None
async def get_session(self, store_options: Optional[dict[str, Any]] = None) -> Optional[dict[str, Any]]:
"""
Retrieve the user session from the store, or None if no session found.
Args:
store_options: Optional options used to pass to the Transaction and State Store.
Returns:
The session, or None if no session found in the store.
"""
state_data = await self._state_store.get(self._state_identifier, store_options)
if state_data:
# Domain check should work for both Pydantic models and plain dicts
if hasattr(state_data, "dict") and callable(state_data.dict):
state_data = state_data.dict()
# In resolver mode, reject sessions with mismatched domain
if self._domain_resolver:
session_domain = self._get_session_domain(state_data)
if not session_domain:
return None
current_domain = await self._resolve_current_domain(store_options)
if self._normalize_url(session_domain) != self._normalize_url(current_domain):
return None
session_data = {k: v for k, v in state_data.items()
if k != "internal"}
return session_data
return None
async def logout(
self,
options: Optional[LogoutOptions] = None,
store_options: Optional[dict[str, Any]] = None
) -> str:
options = options or LogoutOptions()
if not self._domain_resolver:
await self._state_store.delete(self._state_identifier, store_options)
domain = self._domain
else:
# Resolver mode: delete session if domains match
domain = await self._resolve_current_domain(store_options)
state_data = await self._state_store.get(self._state_identifier, store_options)
if state_data:
if hasattr(state_data, "dict") and callable(state_data.dict):
state_data = state_data.dict()
session_domain = self._get_session_domain(state_data)
if session_domain and self._normalize_url(session_domain) == self._normalize_url(domain):
await self._state_store.delete(self._state_identifier, store_options)
# Return logout URL for the current resolved domain
logout_url = URL.create_logout_url(
domain, self._client_id, options.return_to)
return logout_url
async def handle_backchannel_logout(
self,
logout_token: str,
store_options: Optional[dict[str, Any]] = None
) -> None:
"""
Handles backchannel logout requests.
Args:
logout_token: The logout token sent by Auth0
store_options: Options to pass to the state store
"""
if not logout_token:
raise BackchannelLogoutError("Missing logout token")
try:
# Determine domain for JWKS fetch and issuer validation
if self._domain_resolver:
# Resolve domain from request context
resolved_domain = await self._resolve_current_domain(store_options)
# Read iss from unverified token for comparison
try:
unverified = jwt.decode(
logout_token, algorithms=["RS256"],
options={"verify_signature": False}
)
token_issuer = unverified.get("iss", "")
except Exception as e:
raise BackchannelLogoutError(
f"Failed to extract issuer from logout token: {str(e)}"
)
if not token_issuer:
raise BackchannelLogoutError(
"Cannot determine domain: logout token has no valid issuer"
)
# Validate token's iss matches the resolved domain
normalized_iss = self._normalize_url(token_issuer)
normalized_resolved = self._normalize_url(resolved_domain)
if normalized_iss != normalized_resolved:
raise BackchannelLogoutError(
"Logout token issuer does not match the resolved domain"
)
domain = resolved_domain
else:
domain = self._domain
# Fetch JWKS and verify logout token
jwks = await self._get_jwks_cached(domain)
try:
claims = await self._verify_and_decode_jwt(logout_token, jwks, audience=self._client_id)
# Normalized issuer validation
token_issuer = claims.get("iss", "")
expected_issuer = self._normalize_url(domain)
if self._normalize_url(token_issuer) != self._normalize_url(expected_issuer):
raise IssuerValidationError("Logout token issuer mismatch.Ensure your Auth0 domain is configured correctly."
)
except ValueError as e:
raise BackchannelLogoutError(str(e))
except jwt.InvalidSignatureError as e:
raise BackchannelLogoutError(
f"Logout token signature verification failed: {str(e)}"
)
except jwt.InvalidTokenError as e:
raise BackchannelLogoutError(
f"Logout token verification failed: {str(e)}"
)
# Validate the token is a logout token
events = claims.get("events", {})
if "http://schemas.openid.net/event/backchannel-logout" not in events:
raise BackchannelLogoutError(
"Invalid logout token: not a backchannel logout event")
# Delete sessions associated with this token
logout_claims = LogoutTokenClaims(
sub=claims.get("sub"),
sid=claims.get("sid"),
iss=claims.get("iss")
)
await self._state_store.delete_by_logout_token(
logout_claims.dict(), store_options
)
except (jwt.PyJWTError, ValidationError) as e:
raise BackchannelLogoutError(
f"Error processing logout token: {str(e)}")
# ============================================================================
# ACCESS TOKEN MANAGEMENT
# Retrieves, validates, and refreshes access tokens for API calls.
# ============================================================================
async def get_access_token(
self,
store_options: Optional[dict[str, Any]] = None,
audience: Optional[str] = None,
scope: Optional[str] = None,
) -> str:
"""
Retrieves the access token from the store, or calls Auth0 when the access token
is expired and a refresh token is available in the store.
Also updates the store when a new token was retrieved from Auth0.
Args:
store_options: Optional options used to pass to the Transaction and State Store.
Returns:
The access token, retrieved from the store or Auth0.
Raises:
AccessTokenError: If the token is expired and no refresh token is available.
"""
state_data = await self._state_store.get(self._state_identifier, store_options)
# Domain check should work for both Pydantic models and plain dicts
if state_data and hasattr(state_data, "dict") and callable(state_data.dict):
state_data_dict = state_data.dict()
else:
state_data_dict = state_data or {}
# In resolver mode, reject sessions with mismatched domain
if state_data and self._domain_resolver:
session_domain = self._get_session_domain(state_data_dict)
if not session_domain:
raise AccessTokenError(
AccessTokenErrorCode.MISSING_SESSION_DOMAIN,
"Session domain does not match the current domain."
)