redis::entra_id - Rust
Description: Azure Entra ID authentication support for Redis

Skip to main content

## Module entra_id

Source
Available on crate feature `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 `TokenCredential` implementations
- 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

1. The `EntraIdCredentialsProvider` implements the `StreamingCredentialsProvider` trait, which allows clients to subscribe to a stream of credentials.
2. An `EntraIdCredentialsProvider` can be created with one of the public constructors. Each of them creates a specific `TokenCredential` implementation from the `azure_identity` crate.
3. The `EntraIdCredentialsProvider` must be started by calling its `start()` method, which begins a background task for token refresh.
4. The `Client` holds a `StreamingCredentialsProvider` and uses it to authenticate connections.
5. A `Client` can be instantiated with a credentials provider via the `Client::open_with_credentials_provider()` constructor. A credentials provider can also be added to an existing client using the client’s `with_credentials_provider()` function.
6. The `EntraIdCredentialsProvider` keeps the current token and provides it to a `Client` when it establishes a new multiplexed connection. Before the connection gets established, it creates a background task, which subscribes for credential updates.
7. When the token is refreshed, the `EntraIdCredentialsProvider` notifies all subscribers with the new credentials.
8. 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:

- `AzureCliCredential`
- `AzureDeveloperCliCredential`

    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` (from `azure_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

1. “Authentication failed”: Check your credentials and permissions
2. “Token expired”: Ensure automatic refresh is properly configured
3. “Connection timeout”: Check network connectivity and Redis endpoint

## Structs§

ClientCertificate
  A client certificate in PKCS12 (PFX) that can be used for client certificate authentication.
EntraIdCredentialsProvider
  Entra ID credentials provider that uses Azure Identity for authentication

## Constants§

REDIS_SCOPE_DEFAULT
  The default Redis scope for Azure Managed Redis