Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Connect to Azure Managed Redis

Learn how to authenticate to an Azure Managed Redis (AMR) database

The @redis/entraid package lets you authenticate your app to Azure Managed Redis (AMR) using Microsoft Entra ID. You can authenticate using a system-assigned or user-assigned managed identity, a service principal, an auth code flow, or a DefaultAzureCredential instance. The @redis/entraid code fetches and renews the authentication tokens for you automatically.

Install

Install node-redis and @redis/entraid with the following commands:

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

Create a credentials provider instance

A credentials provider object obtains the authentication credentials you need when you connect to Redis (see the Connect section below for a connection example). The EntraIdCredentialsProviderFactory class provides a factory method for each type of credentials provider. Import EntraIdCredentialsProviderFactory with the following code:

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

Then, use the appropriate factory method to create your credentials provider:

The sections below describe these factory functions in more detail.

Provider parameters

All these factory functions receive an object containing the parameters to create the credentials provider. The object generally contains the following fields, but specific factory methods add or omit particular parameters:

tokenManagerConfig

You can configure an authentication token to expire after a certain amount of time, known as its lifetime. You must refresh a token before its lifetime is over to continue using it (see Configurable token lifetimes in the Microsoft identity platform for more information). The tokenManagerConfig object lets you pass parameters to specify how you want to manage token refreshes. The fields of the object are listed below:

authorityConfig

The authorityConfig object has a type field that can take any of the string values default, multi-tenant, or custom. If you use multi-tenant then you must also supply a tenantId field containing the tenant ID string:

// Other fields...
authorityConfig: {
    type: 'multi-tenant',
    tenantId: 'your-tenant-id'
  },
// ...

If you use custom then you must also supply an authorityUrl containing the authority URL string:

// Other fields...
authorityConfig: {
    type: 'custom',
    authorityUrl: 'your-authority-url'
  },
// ...

See Microsoft's Authority docs for more information.

Authenticate with a service principal

Use the createForClientCredentials() factory function to create a credentials provider that authenticates to AMR using a service principal (see the Microsoft documentation to learn more about service principals).

You will need the following details of your service principal to make the connection:

The example below shows how to call createForClientCredentials(). Note that the parameter object includes an extra field here for the client secret.

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
  }
});

If you want to authenticate using a service principal with a certificate, use createForClientCredentialsWithCertificate() to create the credentials provider. This is similar to createForClientCredentials() but it takes a clientCertificate parameter object instead of the clientSecret parameter. This object has the following string fields:

The example below shows how to call createForClientCredentialsWithCertificate() and demonstrates the retry parameter in tokenManagerConfig:

const provider = EntraIdCredentialsProviderFactory.createForClientCredentialsWithCertificate({
  clientId: 'your-client-id',
  clientCertificate: {
    x5c: '<certificate>',
    privateKey: '<private-key>',
    thumbprintSha256: '<certificate-SHA-256-hash>'
  },
  tokenManagerConfig: {
    expirationRefreshRatio: 0.75,
    retry: {
        maxAttempts: 3,
        initialDelayMs: 100,
        maxDelayMs: 1000,
        backoffMultiplier: 2
    }
  }
});

Authenticate with a managed identity

You can authenticate to AMR using a managed identity (see the Microsoft documentation to learn more about managed identities).

For a system-assigned managed identity, use the createForSystemAssignedManagedIdentity() factory function as shown in the example below:

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

For a user-assigned managed identity, use createForUserAssignedManagedIdentity(). Here, the parameter object includes an extra field for the user-assigned client ID.

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

Auth code flow with PKCE

Auth code flow with Proof Key for Code Exchange (PKCE) lets a client app authenticate for access to web APIs and other restricted resources. This requires a redirect URI to return control to your app after authentication. See Microsoft identity platform and OAuth 2.0 authorization code flow for more information.

Use the createForAuthorizationCodeWithPKCE() factory method to use auth code flow with PKCE. The example below shows the extra field redirectUri in the parameter object:

const provider = EntraIdCredentialsProviderFactory.createForAuthorizationCodeWithPKCE({
  clientId: 'your-client-id',
  redirectUri: '<uri-for-your-app>'
});

Authenticate with DefaultAzureCredential

The DefaultAzureCredential class in @azure/identity is designed for use during development. It simplifies authentication by automatically trying different credentials until one succeeds. See DefaultAzureCredential overview in the Microsoft docs for more information.

The example below shows how to use createForDefaultAzureCredential():

import { DefaultAzureCredential } from '@azure/identity';
import { EntraIdCredentialsProviderFactory, REDIS_SCOPE_DEFAULT }
    from '@redis/entraid';

// ...

// Create a DefaultAzureCredential instance
const credential = new DefaultAzureCredential();

// Create a provider using DefaultAzureCredential
const provider = EntraIdCredentialsProviderFactory.createForDefaultAzureCredential({
  // Use the same parameters you would pass to credential.getToken()
  credential,
  scopes: REDIS_SCOPE_DEFAULT, // The Redis scope
  // Optional additional parameters for getToken
  options: {
    // Any options you would normally pass to credential.getToken()
  },
  tokenManagerConfig: {
    expirationRefreshRatio: 0.8
  }
});

Note that when you use createForDefaultAzureCredential(), you must:

Connect

When you have created your credential provider instance, you are ready to connect to AMR. The example below shows how to pass the instance as a parameter to the standard createClient() connection method.

import { createClient } from '@redis/client';
import { EntraIdCredentialsProviderFactory }
    from '@redis/entraid';
    
// Create credentials provider instance...

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

await client.connect();

const size = await client.dbSize();
console.log(`Database size is ${size}`);

RESP2 PUB/SUB limitations

If you are using the RESP2 protocol, you should be aware that pub/sub can cause complications with reauthentication.

After a connection enters PUB/SUB mode, the socket is blocked and can't process out-of-band commands like AUTH. This means that connections in PUB/SUB mode can't be reauthenticated when the tokens are refreshed. As a result, PUB/SUB connections will be evicted by the Redis proxy when their tokens expire. You must reconnect with fresh tokens when this happens.

Note about transactions

If you use transactions in code that also uses token-based authentication, ensure that you use the node-redis client multi/exec API rather than explicit commands to create each transaction (see Execute a transaction for an example of correct usage). This is because the token manager might attempt to reauthenticate while your code issues the separate transaction commands, which will interfere with the transaction. The transaction API handles this case for you safely.

RATE THIS PAGE
Back to top ↑