entra-id only.Expand description
Azure Entra ID authentication support for Redis
This module provides token-based authentication using Azure Entra ID (formerly Azure Active Directory), enabling secure, dynamic authentication for Redis connections with automatic token refresh and streaming credentials support.
§Overview
Token-based authentication allows you to authenticate to Redis using Azure Entra ID tokens instead of static passwords. This provides several benefits:
- Enhanced Security: Tokens have limited lifetimes and can be automatically refreshed
- Centralized Identity Management: Leverage Azure Entra ID for user and service authentication
- Audit and Compliance: Better tracking and auditing of authentication events
- Zero-Trust Architecture: Support for modern security models
§Features
- Automatic Token Refresh & Streaming of Credentials: Seamlessly handle token expiration and stream updated credentials to prevent connection errors due to token expiration
- Multiple Authentication Flows: Service principals, managed identities, and custom
TokenCredentialimplementations - Configurable Refresh Policies: Customizable refresh thresholds and retry behavior via
RetryConfig - Async-First Design: Full async/await support for non-blocking operations with seamless integration for multiplexed connections
§Architecture
§Streaming Credentials Pattern
- The
EntraIdCredentialsProviderimplements theStreamingCredentialsProvidertrait, which allows clients to subscribe to a stream of credentials. - An
EntraIdCredentialsProvidercan be created with one of the public constructors. Each of them creates a specificTokenCredentialimplementation from theazure_identitycrate. - The
EntraIdCredentialsProvidermust be started by calling itsstart()method, which begins a background task for token refresh. - The
Clientholds aStreamingCredentialsProviderand uses it to authenticate connections. - A
Clientcan be instantiated with a credentials provider via theClient::open_with_credentials_provider()constructor. A credentials provider can also be added to an existing client using the client’swith_credentials_provider()function. - The
EntraIdCredentialsProviderkeeps the current token and provides it to aClientwhen it establishes a new multiplexed connection. Before the connection gets established, it creates a background task, which subscribes for credential updates. - When the token is refreshed, the
EntraIdCredentialsProvidernotifies all subscribers with the new credentials. - When a subscriber receives the new credentials, it uses them to re-authenticate itself.
§Quick Start
§Enable the Feature
Add the entra-id feature to your Cargo.toml.
§Basic Usage with DeveloperToolsCredential
use redis::{Client, EntraIdCredentialsProvider, RetryConfig};
// Create the credentials provider using the DeveloperToolsCredential
let mut provider = EntraIdCredentialsProvider::new_developer_tools()?;
provider.start(RetryConfig::default());
// Create Redis client with credentials provider
let client = Client::open_with_credentials_provider(
"redis://your-redis-instance.com:6380",
provider
)?;
// Use the client to get a multiplexed connection
let mut con = client.get_multiplexed_async_connection().await?;
redis::cmd("SET")
.arg("my_key")
.arg(42i32)
.exec_async(&mut con)
.await?;
let result: Option<String> = redis::cmd("GET")
.arg("my_key")
.query_async(&mut con)
.await?;§Authentication Flows
§DeveloperToolsCredential (Recommended for Development)
The DeveloperToolsCredential (from azure_identity) tries the following credential types, in this order, stopping when one provides a token:
AzureCliCredentialAzureDeveloperCliCredential
let mut provider = EntraIdCredentialsProvider::new_developer_tools()?;
provider.start(RetryConfig::default());§Service Principal with Client Secret
For production applications:
let mut provider = EntraIdCredentialsProvider::new_client_secret(
"your-tenant-id".to_string(),
"your-client-id".to_string(),
"your-client-secret".to_string(),
)?;
provider.start(RetryConfig::default());§Service Principal with Certificate
For enhanced security:
// Load certificate from file
let certificate_base64 = fs::read_to_string("path/to/base64_pkcs12_certificate")
.expect("Base64 PKCS12 certificate not found.")
.trim()
.to_string();
// Create the credentials provider using service principal with client certificate
let mut provider = EntraIdCredentialsProvider::new_client_certificate(
"your-tenant-id".to_string(),
"your-client-id".to_string(),
ClientCertificate {
base64_pkcs12: certificate_base64, // Base64 encoded PKCS12 data
password: None,
},
)?;
provider.start(RetryConfig::default());§Managed Identity
For Azure-hosted applications:
// System-assigned managed identity
let mut provider = EntraIdCredentialsProvider::new_system_assigned_managed_identity()?;
provider.start(RetryConfig::default());
// User-assigned managed identity
let mut provider = EntraIdCredentialsProvider::new_user_assigned_managed_identity()?;
provider.start(RetryConfig::default());For user-assigned managed identity with custom scopes and identity specification:
let mut provider = EntraIdCredentialsProvider::new_user_assigned_managed_identity_with_scopes(
vec!["your-scope".to_string()],
Some(ManagedIdentityCredentialOptions {
// Specify the user-assigned identity using one of:
user_assigned_id: Some(UserAssignedId::ClientId("your-client-id".to_string())),
// or: user_assigned_id: Some(UserAssignedId::ObjectId("your-object-id".to_string())),
// or: user_assigned_id: Some(UserAssignedId::ResourceId("your-resource-id".to_string())),
..Default::default()
}),
)?;
provider.start(RetryConfig::default());§Advanced Configuration
§Token Refresh with Custom Configuration
The token refresh behavior can be customized by providing a RetryConfig when starting the provider:
let mut provider = EntraIdCredentialsProvider::new_developer_tools()?;
let retry_config = RetryConfig::default()
.set_number_of_retries(3)
.set_min_delay(Duration::from_millis(100))
.set_max_delay(Duration::from_secs(30))
.set_exponent_base(2.0);
provider.start(retry_config);§Error Handling
The library provides comprehensive error handling for authentication and token refresh failures. The background token refresh service will automatically retry failed token refreshes according to the retry configuration. Once the maximum number of attempts is reached, the service will stop retrying and the underlying error will be propagated to the subscribers.
§Best Practices
§Use Appropriate Credential Types
- Development:
DeveloperToolsCredential(fromazure_identity) - Production Services: Service Principal with certificate
- Azure-hosted Apps: Managed Identity
§Security Considerations
- Store client secrets securely (Azure Key Vault, environment variables)
- Use certificates instead of secrets when possible
§Compatibility
- Redis Versions: Compatible with Redis 6.0+ (ACL support required)
- Azure Redis: Fully compatible with Azure Cache for Redis
§Troubleshooting
§Common Issues
- “Authentication failed”: Check your credentials and permissions
- “Token expired”: Ensure automatic refresh is properly configured
- “Connection timeout”: Check network connectivity and Redis endpoint
Structs§
- Client
Certificate - A client certificate in PKCS12 (PFX) that can be used for client certificate authentication.
- Entra
IdCredentials Provider - Entra ID credentials provider that uses Azure Identity for authentication
Constants§
- REDIS_
SCOPE_ DEFAULT - The default Redis scope for Azure Managed Redis