1
0
mirror of https://github.com/redis/node-redis.git synced 2025-08-06 02:15:48 +03:00
Files
node-redis/packages/entraid/README.md
Bobby I. 6d21de3f31 feat(auth): add Entra ID identity provider integration for Redis client authentication (#2877)
* feat(auth): refactor authentication mechanism to use CredentialsProvider

- Introduce new credential providers: AsyncCredentialsProvider, StreamingCredentialsProvider
- Update client handshake process to use the new CredentialsProviders and to support async credentials fetch / credentials refresh
- Internal conversion of username/password to a CredentialsProvider
- Modify URL parsing to accommodate the new authentication structure
- Tests

* feat(auth): auth extensions

Introduces TokenManager and supporting classes to handle token acquisition, automatic
refresh, and updates via identity providers. This foundation enables consistent
authentication token management across different identity provider implementations.

Key additions:
- Add TokenManager to obtain and maintain auth tokens from identity providers
  with automated refresh scheduling based on TTL and configurable thresholds
- Add IdentityProvider interface for token acquisition from auth providers
- Implement Token class for managing token state and TTL tracking
- Include configurable retry mechanism with exponential backoff and jitter
- Add comprehensive test suite covering refresh cycles and error handling

This change establishes the core infrastructure needed for reliable token
lifecycle management across different authentication providers.

* feat(auth): add Entra ID identity provider integration

Introduces Entra ID (former Azure AD) authentication support with multiple authentication flows
and automated token lifecycle management.

Key additions:
- Add EntraIdCredentialsProvider for handling Entra ID authentication flows
- Implement MSALIdentityProvider to integrate with MSAL/EntraID authentication library
- Add support for multiple authentication methods:
  - Managed identities (system and user-assigned)
  - Client credentials with certificate
  - Client credentials with secret
  - Authorization Code flow with PKCE
- Add factory class with builder methods for each authentication flow
- Include sample Express server implementation for Authorization Code flow
- Add comprehensive configuration options for authority and token management

* feat(test-utils): improve cluster testing

- Add support for configuring replica authentication with 'masterauth'
- Allow default client configuration during test cluster creation

This improves the testing framework's flexibility by automatically
configuring replica authentication when '--requirepass' is used and
enabling custom client configurations across cluster nodes.

* feat(auth): add EntraId integration tests

- Add integration tests for token renewal and re-authentication flows
- Update credentials provider to use uniqueId as username instead of account username
- Add test utilities for loading Redis endpoint configurations
- Split TypeScript configs into separate files for samples and integration tests
- Remove `@redis/authx` package and nest it under `@`
2025-01-30 10:29:19 +02:00

4.5 KiB

@redis/entraid

Secure token-based authentication for Redis clients using Microsoft Entra ID (formerly Azure Active Directory).

Features

  • Token-based authentication using Microsoft Entra ID
  • Automatic token refresh before expiration
  • Automatic re-authentication of all connections after token refresh
  • Support for multiple authentication flows:
    • Managed identities (system-assigned and user-assigned)
    • Service principals (with or without certificates)
    • Authorization Code with PKCE flow
  • Built-in retry mechanisms for transient failures

Installation

npm install @redis/client
npm install @redis/entraid

Getting Started

The first step to using @redis/entraid is choosing the right credentials provider for your authentication needs. The EntraIdCredentialsProviderFactory class provides several factory methods to create the appropriate provider:

  • createForSystemAssignedManagedIdentity: Use when your application runs in Azure with a system-assigned managed identity
  • createForUserAssignedManagedIdentity: Use when your application runs in Azure with a user-assigned managed identity
  • createForClientCredentials: Use when authenticating with a service principal using client secret
  • createForClientCredentialsWithCertificate: Use when authenticating with a service principal using a certificate
  • createForAuthorizationCodeWithPKCE: Use for interactive authentication flows in user applications

Usage Examples

Service Principal Authentication

import { createClient } from '@redis/client';
import { EntraIdCredentialsProviderFactory } from '@redis/entraid';

const provider = EntraIdCredentialsProviderFactory.createForClientCredentials({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
  authorityConfig: {
    type: 'multi-tenant',
    tenantId: 'your-tenant-id'
  },
  tokenManagerConfig: {
    expirationRefreshRatio: 0.8 // Refresh token after 80% of its lifetime
  }
});

const client = createClient({
  url: 'redis://your-host',
  credentialsProvider: provider
});

await client.connect();

System-Assigned Managed Identity

const provider = EntraIdCredentialsProviderFactory.createForSystemAssignedManagedIdentity({
  clientId: 'your-client-id',
  tokenManagerConfig: {
    expirationRefreshRatio: 0.8
  }
});

User-Assigned Managed Identity

const provider = EntraIdCredentialsProviderFactory.createForUserAssignedManagedIdentity({
  clientId: 'your-client-id',
  userAssignedClientId: 'your-user-assigned-client-id',
  tokenManagerConfig: {
    expirationRefreshRatio: 0.8
  }
});

Important Limitations

RESP2 PUB/SUB Limitations

When using RESP2 (Redis Serialization Protocol 2), there are important limitations with PUB/SUB:

  • No Re-Authentication in PUB/SUB Mode: In RESP2, once a connection enters PUB/SUB mode, the socket is blocked and cannot process out-of-band commands like AUTH. This means that connections in PUB/SUB mode cannot be re-authenticated when tokens are refreshed.
  • Connection Eviction: As a result, PUB/SUB connections will be evicted by the Redis proxy when their tokens expire. The client will need to establish new connections with fresh tokens.

Transaction Safety

When using token-based authentication, special care must be taken with Redis transactions. The token manager runs in the background and may attempt to re-authenticate connections at any time by sending AUTH commands. This can interfere with manually constructed transactions.

Always use the official transaction API provided by the client:

// Correct way to handle transactions
const multi = client.multi();
multi.set('key1', 'value1');
multi.set('key2', 'value2');
await multi.exec();

Avoid: Manual Transaction Construction

Do not manually construct transactions by sending individual MULTI/EXEC commands:

// Incorrect and potentially dangerous
await client.sendCommand(['MULTI']);
await client.sendCommand(['SET', 'key1', 'value1']);
await client.sendCommand(['SET', 'key2', 'value2']);
await client.sendCommand(['EXEC']); // Risk of AUTH command being injected before EXEC

Error Handling

The provider includes built-in retry mechanisms for transient errors:

const provider = EntraIdCredentialsProviderFactory.createForClientCredentials({
  // ... other config ...
  tokenManagerConfig: {
    retry: {
      maxAttempts: 3,
      initialDelayMs: 100,
      maxDelayMs: 1000,
      backoffMultiplier: 2
    }
  }
});