kiarina-lib-firebase-auth
Firebase authentication library with REST API integration and automatic token management.
Purpose
kiarina-lib-firebase-auth provides a simple and secure way to manage Firebase authentication using REST APIs. This library enables custom token exchange and automatic ID token lifecycle management with configuration management using pydantic-settings-manager.
Key features:
- Custom token exchange for refresh/ID tokens via Firebase REST API
- Automatic ID token lifecycle management with
TokenManager - Token refresh 5 minutes before expiration
- Thread-safe token refresh with
asyncio.Lock - Secure API key management with SecretStr
- Multi-configuration support for different projects/environments
- Async-only API for modern Python applications
- Environment variable configuration
Installation
pip install kiarina-lib-firebase-auth
Quick Start
Basic Usage
from kiarina.lib.firebase.auth import (
TokenManager,
exchange_custom_token,
settings_manager,
)
# Configure settings
settings_manager.user_config = {
"default": {
"project_id": "your-project-id",
"api_key": "your-firebase-api-key",
}
}
# Get settings
settings = settings_manager.get_settings()
api_key = settings.api_key.get_secret_value()
# Exchange custom token for ID and refresh tokens
custom_token = "your_custom_token_here"
token_data = await exchange_custom_token(custom_token, api_key)
# Create token manager for automatic token refresh
manager = TokenManager(
api_key=api_key,
token_data=token_data,
)
# Get ID token (automatically refreshes when needed)
id_token = await manager.get_id_token()
print(f"ID Token: {id_token}")
# Use the ID token for Firebase API calls
# The token will be automatically refreshed 5 minutes before expiration
Manual Token Refresh
from kiarina.lib.firebase.auth import refresh_id_token
# Manually refresh ID token using refresh token
token_data = await refresh_id_token(
refresh_token="your_refresh_token",
api_key="your_api_key",
)
print(f"New ID Token: {token_data.id_token}")
print(f"Expires at: {token_data.expires_at}")
API Reference
Settings
FirebaseAuthSettings
Configuration for Firebase authentication.
from pydantic import SecretStr
from kiarina.lib.firebase.auth import FirebaseAuthSettings
settings = FirebaseAuthSettings(
project_id="your-project-id",
api_key=SecretStr("your-firebase-api-key"),
)
Fields:
project_id: str- Firebase project IDapi_key: SecretStr- Firebase Web API Key (obtain from Firebase Console)
Functions
exchange_custom_token(custom_token: str, api_key: str) -> TokenData
Exchange a Firebase custom token for an ID token and refresh token.
Parameters:
custom_token: str- Firebase custom token (JWT)api_key: str- Firebase Web API Key
Returns:
TokenData- Containsrefresh_token,id_token, andexpires_at
Raises:
InvalidCustomTokenError- If the custom token is invalid or expiredFirebaseAPIError- If Firebase API returns an error
refresh_id_token(refresh_token: str, api_key: str) -> TokenData
Refresh ID token using refresh token.
Parameters:
refresh_token: str- Firebase refresh tokenapi_key: str- Firebase Web API Key
Returns:
TokenData- Contains newrefresh_token,id_token, andexpires_at
Raises:
InvalidRefreshTokenError- If refresh token is invalid or expiredFirebaseAPIError- If Firebase API returns an error
Classes
TokenManager
Service class for automatic ID token lifecycle management.
from kiarina.lib.firebase.auth import TokenManager, TokenData
# Option 1: With token_data (recommended)
manager = TokenManager(
api_key="your_api_key",
token_data=token_data,
refresh_buffer_seconds=300, # Default: 5 minutes
)
# Option 2: With refresh_token only
manager = TokenManager(
api_key="your_api_key",
refresh_token="your_refresh_token",
refresh_buffer_seconds=300, # Default: 5 minutes
)
# Option 3: With token_data_cache for persistent storage
manager = TokenManager(
api_key="your_api_key",
token_data_cache=my_cache_implementation,
refresh_buffer_seconds=300, # Default: 5 minutes
)
Constructor Parameters (all keyword-only):
api_key: str- Required. Firebase Web API Keyrefresh_token: str | None- Firebase refresh token (at least one ofrefresh_token,token_data, ortoken_data_cacheis required)token_data: TokenData | None- Initial token data (at least one ofrefresh_token,token_data, ortoken_data_cacheis required)token_data_cache: TokenDataCache | None- Cache implementation for persistent token storage (at least one ofrefresh_token,token_data, ortoken_data_cacheis required)refresh_buffer_seconds: int- Refresh buffer time in seconds (default: 300)
Methods:
async get_id_token() -> str- Get current ID token (auto-refreshes if needed)async refresh() -> TokenData- Manually refresh ID token
Properties:
id_token: str- Current ID tokenexpires_at: datetime- Token expiration time (UTC)
TokenData
Schema for Firebase authentication token data.
Fields:
refresh_token: str- Refresh token for getting new ID tokensid_token: str- Firebase ID token (JWT)expires_at: datetime- ID token expiration time (UTC)
Class Methods:
from_api_response(id_token: str, refresh_token: str, expires_in: int, *, issued_at: datetime | None = None) -> TokenData- Create TokenData from Firebase API response
TokenDataCache
Protocol for token data cache implementations.
Implementations should provide persistent storage for TokenData, allowing TokenManager to automatically save and restore token state.
from kiarina.lib.firebase.auth import TokenDataCache, TokenData
class MyTokenCache(TokenDataCache):
async def get(self) -> TokenData:
# Load token data from persistent storage
...
async def set(self, token_data: TokenData) -> None:
# Save token data to persistent storage
...
# Use with TokenManager
manager = TokenManager(
api_key="your_api_key",
token_data_cache=MyTokenCache(),
)
Methods:
async get() -> TokenData- Retrieve cached token dataasync set(token_data: TokenData) -> None- Store token data in cache
Exceptions
FirebaseAuthError
Base exception for Firebase Auth errors.
InvalidCustomTokenError
Raised when custom token is invalid or expired.
InvalidRefreshTokenError
Raised when refresh token is invalid or expired.
FirebaseAPIError
Raised when Firebase API returns an error response.
Attributes:
status_code: int | None- HTTP status codeerror_code: str | None- Firebase error code
Configuration
YAML Configuration
kiarina.lib.firebase.auth:
default:
project_id: your-project-id
api_key: your-firebase-api-key
production:
project_id: prod-project-id
api_key: ${FIREBASE_API_KEY} # From environment variable
Environment Variables
Settings can be configured via environment variables with the KIARINA_LIB_FIREBASE_AUTH_ prefix:
export KIARINA_LIB_FIREBASE_AUTH_PROJECT_ID=your-project-id
export KIARINA_LIB_FIREBASE_AUTH_API_KEY=your-firebase-api-key
Multi-Configuration Support
from kiarina.lib.firebase.auth import settings_manager
# Configure multiple environments
settings_manager.user_config = {
"development": {
"project_id": "dev-project",
"api_key": "dev-api-key",
},
"production": {
"project_id": "prod-project",
"api_key": "prod-api-key",
},
}
# Get settings for specific environment
dev_settings = settings_manager.get_settings("development")
prod_settings = settings_manager.get_settings("production")
Testing
This package includes integration tests that require Firebase Admin SDK and Google Cloud authentication.
Setup
- Create a test settings file:
# test_settings.yaml
kiarina.lib.google.auth:
default:
type: service_account
project_id: your-project-id
service_account_email: your-service-account@your-project.iam.gserviceaccount.com
service_account_file: ~/.gcp/service-account/your-project/key.json
kiarina.lib.firebase.auth:
default:
project_id: your-project-id
api_key: your-firebase-api-key
- Set environment variable:
export KIARINA_LIB_FIREBASE_AUTH_TEST_SETTINGS_FILE=/path/to/test_settings.yaml
- Run tests:
pytest tests/
Dependencies
httpx>=0.28.1- Async HTTP client for Firebase REST APIpydantic>=2.10.6- Data validation and settings managementpydantic-settings>=2.10.1- Settings management from environmentpydantic-settings-manager>=2.3.0- Multi-configuration settings management
Development Dependencies
firebase-admin>=6.6.0- Firebase Admin SDK (for testing)kiarina-lib-google-auth>=1.22.0- Google Cloud authentication (for testing)
License
This project is licensed under the MIT License.
Related Projects
- kiarina-lib-google-auth - Google Cloud authentication library
- pydantic-settings-manager - Multi-configuration settings management
Metadata
Release files for kiarina-lib-firebase-auth 1.37.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| kiarina_lib_firebase_auth-1.37.0.tar.gz | 9.7 kB | Without provenance | Details for kiarina_lib_firebase_auth-1.37.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| kiarina_lib_firebase_auth-1.37.0-py3-none-any.whl | Python 3 | none | any | Details for kiarina_lib_firebase_auth-1.37.0-py3-none-any.whl |
Total release size: 21.8 kB
Release files / kiarina_lib_firebase_auth-1.37.0.tar.gz
| Download URL | kiarina_lib_firebase_auth-1.37.0.tar.gz |
|---|---|
| Size | 9.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f2ce5de1bbe2e6197c83e0fad74859b6092f36125493f35c4f50d2f786993e54
|
|
BLAKE2b-256 checksum How to use checksums |
ff5cbd9a62e5cc558111ccaa1a23cebcc514d44887e7af26bd8e3613116e563d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Release files / kiarina_lib_firebase_auth-1.37.0-py3-none-any.whl
| Download URL | kiarina_lib_firebase_auth-1.37.0-py3-none-any.whl |
|---|---|
| Size | 12.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
76af7d64bad4b2ccbeee5c74c524b13f0a29b56dcb6347eefa29035009e50275
|
|
BLAKE2b-256 checksum How to use checksums |
3793f7ed01037c186d4f56d42f007e6e47e043a22f083c31f647727ad2424b27
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Security for kiarina-lib-firebase-auth 1.37.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.