Exceptions
Custom exceptions raised by cognito-auth.
AuthenticationError
AuthenticationError
Base exception for all authentication errors. Use this to catch any token-related failure:
from cognito_auth.exceptions import AuthenticationError
try:
user = User(
oidc_data_header=token,
access_token_header=access_token,
region="eu-west-2",
)
except AuthenticationError as e:
# Catches InvalidTokenError, ExpiredTokenError, and MissingTokenError
print(f"Authentication failed: {e}")
InvalidTokenError
InvalidTokenError
Bases: AuthenticationError
Raised when token is invalid or verification fails
Raised when a JWT token fails signature verification or is malformed.
Common causes:
- Token signature doesn't match public key
- Token is malformed or corrupted
- Token was not issued by the expected ALB or Cognito User Pool
Example:
from cognito_auth import User
from cognito_auth.exceptions import InvalidTokenError
try:
user = User(
oidc_data_header="invalid-token",
access_token_header="invalid-token",
region="eu-west-2",
verify_tokens=True
)
except InvalidTokenError as e:
print(f"Token validation failed: {e}")
ExpiredTokenError
ExpiredTokenError
Bases: AuthenticationError
Raised when token has expired
Raised when a JWT token has expired.
Common causes:
- User's session has timed out
- Token expiration time (
expclaim) is in the past - System clock skew
Example:
from cognito_auth import User
from cognito_auth.exceptions import ExpiredTokenError
try:
user = User(
oidc_data_header=expired_token,
access_token_header=access_token,
region="eu-west-2",
verify_tokens=True
)
except ExpiredTokenError as e:
print(f"Token expired: {e}")
# Redirect user to re-authenticate
MissingTokenError
MissingTokenError
Bases: AuthenticationError
Raised when required token headers are missing
Raised when required Cognito headers are missing from the request.
Common causes:
- Application not behind ALB with OIDC authentication enabled
- Headers not properly forwarded by load balancer
- Testing without dev mode enabled
Example:
from cognito_auth import User
from cognito_auth.exceptions import MissingTokenError
try:
user = User(
oidc_data_header=None, # Missing header
access_token_header="token",
region="eu-west-2",
verify_tokens=True
)
except MissingTokenError as e:
print(f"Required headers missing: {e}")
Handling Exceptions
Framework auth classes handle these exceptions automatically:
StreamlitAuth:
DashAuth / FastAPIAuth / GradioAuth:
Manual handling:
from cognito_auth import User
from cognito_auth.exceptions import (
AuthenticationError,
InvalidTokenError,
ExpiredTokenError,
MissingTokenError,
)
try:
user = User(
oidc_data_header=oidc_token,
access_token_header=access_token,
region="eu-west-2",
verify_tokens=True
)
except MissingTokenError:
# Redirect to login
pass
except ExpiredTokenError:
# Session expired, re-authenticate
pass
except InvalidTokenError:
# Tampered or invalid token
pass
except AuthenticationError:
# Catch-all for any authentication failure
pass