Integrare Cache di Azure per Redis con Service Connector
Articolo
È possibile connettere cache di Azure per Redis ad altri servizi cloud usando Service Connector. Questo articolo illustra i metodi e i client di autenticazione supportati e fornisce codice di esempio. Vengono inoltre visualizzati i nomi e i valori predefiniti delle variabili di ambiente (o configurazione spring boot) che si ottengono quando si crea la connessione al servizio.
Servizi di calcolo supportati
È possibile usare Service Connector per connettere i servizi di calcolo seguenti a cache di Azure per Redis:
Servizio app di Azure
App contenitore di Azure
Funzioni di Azure
Servizio Azure Kubernetes (AKS)
Azure Spring Apps
Autenticazione e tipi di client supportati
La tabella seguente illustra le combinazioni di metodi di autenticazione e client supportati per la connessione del servizio di calcolo a cache di Azure per Redis tramite Service Connector. "Sì" indica che la combinazione è supportata. "No" significa che non è supportato.
Tipo client
Identità gestita assegnata dal sistema
Identità gestita assegnata dall'utente
Stringa di segreto/connessione
Entità servizio
.NET
Sì
Sì
Sì
Sì
Go
No
No
Sì
No
Java
Sì
Sì
Sì
Sì
Java - Spring Boot
No
No
Sì
No
Node.js
Sì
Sì
Sì
Sì
Python
Sì
Sì
Sì
Sì
Nessuno
Sì
Sì
Sì
Sì
Tutti i tipi di client, ad eccezione di Go e Java - Spring Boot, possono usare uno dei metodi di autenticazione a cui si fa riferimento nella tabella per connettersi a cache di Azure per Redis tramite Service Connector. Gli unici metodi di autenticazione supportati per Go e Java - Spring Boot sono secret/stringa di connessione o entità servizio.
Nomi di variabili di ambiente predefiniti o proprietà dell'applicazione e codice di esempio
Usare i nomi delle variabili di ambiente e le proprietà dell'applicazione seguenti per connettere i servizi di calcolo al server Redis. Per altre informazioni sulle convenzioni di denominazione, vedere l'articolo Elementi interni di Service Connector.
Identità gestita assegnata dal sistema
Nome variabile di ambiente predefinito
Descrizione
Valore di esempio
AZURE_REDIS_HOST
Endpoint Redis
<RedisName>.redis.cache.windows.net
Codice di esempio
I passaggi e il codice seguenti illustrano come usare un'identità gestita assegnata dal sistema per connettersi a Redis.
Aggiungere la logica di autenticazione con le variabili di ambiente impostate da Service Connector. Per altre informazioni, vedere Estensione Microsoft.Azure.StackExchangeRedis.
using StackExchange.Redis;
var cacheHostName = Environment.GetEnvironmentVariable("AZURE_REDIS_HOST");
var configurationOptions = ConfigurationOptions.Parse($"{cacheHostName}:6380");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
// For user-assigned identity.
// var managedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// await configurationOptions.ConfigureForAzureWithUserAssignedManagedIdentityAsync(managedIdentityClientId);
// Service principal secret.
// var clientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// var tenantId = Environment.GetEnvironmentVariable("AZURE_REDIS_TENANTID");
// var secret = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTSECRET");
// await configurationOptions.ConfigureForAzureWithServicePrincipalAsync(clientId, tenantId, secret);
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
Aggiungere la dipendenza seguente nel pom.xml file:
Aggiungere la logica di autenticazione con le variabili di ambiente impostate da Service Connector. Per altre informazioni, vedere Azure-AAD-Authentication-With-Jedis.
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import java.net.URI;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
// For user-assigned identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().managedIdentityClientId(clientId).build();
// For AKS workload identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().workloadIdentityClientId(clientId).build();
// For service principal.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// String secret = System.getenv("AZURE_REDIS_CLIENTSECRET");
// String tenant = System.getenv("AZURE_REDIS_TENANTID");
// ClientSecretCredential defaultAzureCredential = new ClientSecretCredentialBuilder().tenantId(tenant).clientId(clientId).clientSecret(secret).build();
String token = defaultAzureCredential
.getToken(new TokenRequestContext()
.addScopes("https://redis.azure.com/.default")).block().getToken();
// SSL connection is required.
boolean useSsl = true;
// TODO: Replace Host Name with Azure Cache for Redis Host Name.
String username = extractUsernameFromToken(token);
String cacheHostname = System.getenv("AZURE_REDIS_HOST");
// Create Jedis client and connect to Azure Cache for Redis over the TLS/SSL port using the access token as password.
// Note, Redis Cache host name and port are required below.
Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
.password(token) // Microsoft Entra access token as password is required.
.user(username) // Username is Required
.ssl(useSsl) // SSL Connection is Required
.build());
// Set a value against your key in the Redis cache.
jedis.set("Az:key", "testValue");
System.out.println(jedis.get("Az:key"));
// Close the Jedis Client
jedis.close();
Non ancora supportato.
Installare le dipendenze.
pip install redis azure-identity
Aggiungere la logica di autenticazione con le variabili di ambiente impostate da Service Connector. Per altre informazioni, vedere azure-aad-auth-with-redis-py.
import os
import time
import logging
import redis
import base64
import json
from azure.identity import DefaultAzureCredential
host = os.getenv('AZURE_REDIS_HOST')
scope = "https://redis.azure.com/.default"
port = 6380 # Required
def extract_username_from_token(token):
parts = token.split('.')
base64_str = parts[1]
if len(base64_str) % 4 == 2:
base64_str += "=="
elif len(base64_str) % 4 == 3:
base64_str += "="
json_bytes = base64.b64decode(base64_str)
json_str = json_bytes.decode('utf-8')
jwt = json.loads(json_str)
return jwt['oid']
def re_authentication():
_LOGGER = logging.getLogger(__name__)
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For service principal.
# tenant_id = os.getenv("AZURE_TENANT_ID")
# client_id = os.getenv("AZURE_CLIENT_ID")
# client_secret = os.getenv("AZURE_CLIENT_SECRET")
# cred = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
token = cred.get_token(scope)
user_name = extract_username_from_token(token.token)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
max_retry = 3
for index in range(max_retry):
try:
if _need_refreshing(token):
_LOGGER.info("Refreshing token...")
tmp_token = cred.get_token(scope)
if tmp_token:
token = tmp_token
r.execute_command("AUTH", user_name, token.token)
r.set("Az:key1", "value1")
t = r.get("Az:key1")
print(t)
break
except redis.ConnectionError:
_LOGGER.info("Connection lost. Reconnecting.")
token = cred.get_token(scope)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
except Exception:
_LOGGER.info("Unknown failures.")
break
def _need_refreshing(token, refresh_offset=300):
return not token or token.expires_on - time.time() < refresh_offset
if __name__ == '__main__':
re_authentication()
import { createClient } from "redis";
import { DefaultAzureCredential } from "@azure/identity";
function extractUsernameFromToken(accessToken: AccessToken): string{
const base64Metadata = accessToken.token.split(".")[1];
const { oid } = JSON.parse(
Buffer.from(base64Metadata, "base64").toString("utf8"),
);
return oid;
}
async function main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_REDIS_TENANTID;
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const clientSecret = process.env.AZURE_REDIS_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
const redisScope = "https://redis.azure.com/.default";
let accessToken = await credential.getToken(redisScope);
console.log("access Token", accessToken);
const host = process.env.AZURE_REDIS_HOST;
// Create redis client and connect to Azure Cache for Redis over the TLS port using the access token as password.
const client = createClient({
username: extractUsernameFromToken(accessToken),
password: accessToken.token,
url: `redis://${host}:6380`,
pingInterval: 100000,
socket: {
tls: true,
keepAlive: 0
},
});
client.on("error", (err) => console.log("Redis Client Error", err));
await client.connect();
// Set a value against your key in Azure Redis Cache.
await client.set("Az:key", "value1312");
// Get value of your key in Azure Redis Cache.
console.log("value-", await client.get("Az:key"));
}
main().catch((err) => {
console.log("error code: ", err.code);
console.log("error message: ", err.message);
console.log("error stack: ", err.stack);
});
Per altre lingue, è possibile usare la libreria client di Azure Identity (e le informazioni di connessione impostate da Service Connector per le variabili di ambiente) per connettersi a cache di Azure per Redis.
Identità gestita assegnata dall'utente
Nome variabile di ambiente predefinito
Descrizione
Valore di esempio
AZURE_REDIS_HOST
Endpoint Redis
<RedisName>.redis.cache.windows.net
AZURE_REDIS_CLIENTID
ID client dell'identità gestita
<client-ID>
Codice di esempio
I passaggi e il codice seguenti illustrano come usare un'identità gestita assegnata dall'utente per connettersi a Redis.
Aggiungere la logica di autenticazione con le variabili di ambiente impostate da Service Connector. Per altre informazioni, vedere Estensione Microsoft.Azure.StackExchangeRedis.
using StackExchange.Redis;
var cacheHostName = Environment.GetEnvironmentVariable("AZURE_REDIS_HOST");
var configurationOptions = ConfigurationOptions.Parse($"{cacheHostName}:6380");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
// For user-assigned identity.
// var managedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// await configurationOptions.ConfigureForAzureWithUserAssignedManagedIdentityAsync(managedIdentityClientId);
// Service principal secret.
// var clientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// var tenantId = Environment.GetEnvironmentVariable("AZURE_REDIS_TENANTID");
// var secret = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTSECRET");
// await configurationOptions.ConfigureForAzureWithServicePrincipalAsync(clientId, tenantId, secret);
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
Aggiungere la dipendenza seguente nel pom.xml file:
Aggiungere la logica di autenticazione con le variabili di ambiente impostate da Service Connector. Per altre informazioni, vedere Azure-AAD-Authentication-With-Jedis.
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import java.net.URI;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
// For user-assigned identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().managedIdentityClientId(clientId).build();
// For AKS workload identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().workloadIdentityClientId(clientId).build();
// For service principal.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// String secret = System.getenv("AZURE_REDIS_CLIENTSECRET");
// String tenant = System.getenv("AZURE_REDIS_TENANTID");
// ClientSecretCredential defaultAzureCredential = new ClientSecretCredentialBuilder().tenantId(tenant).clientId(clientId).clientSecret(secret).build();
String token = defaultAzureCredential
.getToken(new TokenRequestContext()
.addScopes("https://redis.azure.com/.default")).block().getToken();
// SSL connection is required.
boolean useSsl = true;
// TODO: Replace Host Name with Azure Cache for Redis Host Name.
String username = extractUsernameFromToken(token);
String cacheHostname = System.getenv("AZURE_REDIS_HOST");
// Create Jedis client and connect to Azure Cache for Redis over the TLS/SSL port using the access token as password.
// Note, Redis Cache host name and port are required below.
Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
.password(token) // Microsoft Entra access token as password is required.
.user(username) // Username is Required
.ssl(useSsl) // SSL Connection is Required
.build());
// Set a value against your key in the Redis cache.
jedis.set("Az:key", "testValue");
System.out.println(jedis.get("Az:key"));
// Close the Jedis Client
jedis.close();
Non ancora supportato.
Installare le dipendenze.
pip install redis azure-identity
Aggiungere la logica di autenticazione con le variabili di ambiente impostate da Service Connector. Per altre informazioni, vedere azure-aad-auth-with-redis-py.
import os
import time
import logging
import redis
import base64
import json
from azure.identity import DefaultAzureCredential
host = os.getenv('AZURE_REDIS_HOST')
scope = "https://redis.azure.com/.default"
port = 6380 # Required
def extract_username_from_token(token):
parts = token.split('.')
base64_str = parts[1]
if len(base64_str) % 4 == 2:
base64_str += "=="
elif len(base64_str) % 4 == 3:
base64_str += "="
json_bytes = base64.b64decode(base64_str)
json_str = json_bytes.decode('utf-8')
jwt = json.loads(json_str)
return jwt['oid']
def re_authentication():
_LOGGER = logging.getLogger(__name__)
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For service principal.
# tenant_id = os.getenv("AZURE_TENANT_ID")
# client_id = os.getenv("AZURE_CLIENT_ID")
# client_secret = os.getenv("AZURE_CLIENT_SECRET")
# cred = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
token = cred.get_token(scope)
user_name = extract_username_from_token(token.token)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
max_retry = 3
for index in range(max_retry):
try:
if _need_refreshing(token):
_LOGGER.info("Refreshing token...")
tmp_token = cred.get_token(scope)
if tmp_token:
token = tmp_token
r.execute_command("AUTH", user_name, token.token)
r.set("Az:key1", "value1")
t = r.get("Az:key1")
print(t)
break
except redis.ConnectionError:
_LOGGER.info("Connection lost. Reconnecting.")
token = cred.get_token(scope)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
except Exception:
_LOGGER.info("Unknown failures.")
break
def _need_refreshing(token, refresh_offset=300):
return not token or token.expires_on - time.time() < refresh_offset
if __name__ == '__main__':
re_authentication()
import { createClient } from "redis";
import { DefaultAzureCredential } from "@azure/identity";
function extractUsernameFromToken(accessToken: AccessToken): string{
const base64Metadata = accessToken.token.split(".")[1];
const { oid } = JSON.parse(
Buffer.from(base64Metadata, "base64").toString("utf8"),
);
return oid;
}
async function main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_REDIS_TENANTID;
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const clientSecret = process.env.AZURE_REDIS_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
const redisScope = "https://redis.azure.com/.default";
let accessToken = await credential.getToken(redisScope);
console.log("access Token", accessToken);
const host = process.env.AZURE_REDIS_HOST;
// Create redis client and connect to Azure Cache for Redis over the TLS port using the access token as password.
const client = createClient({
username: extractUsernameFromToken(accessToken),
password: accessToken.token,
url: `redis://${host}:6380`,
pingInterval: 100000,
socket: {
tls: true,
keepAlive: 0
},
});
client.on("error", (err) => console.log("Redis Client Error", err));
await client.connect();
// Set a value against your key in Azure Redis Cache.
await client.set("Az:key", "value1312");
// Get value of your key in Azure Redis Cache.
console.log("value-", await client.get("Az:key"));
}
main().catch((err) => {
console.log("error code: ", err.code);
console.log("error message: ", err.message);
console.log("error stack: ", err.stack);
});
Per altre lingue, è possibile usare la libreria client di Azure Identity (e le informazioni di connessione impostate da Service Connector per le variabili di ambiente) per connettersi a cache di Azure per Redis.
Stringa di connessione
Avviso
È consigliabile usare il flusso di autenticazione più sicuro disponibile. Il flusso di autenticazione descritto qui richiede un livello di attendibilità molto elevato nell'applicazione e comporta rischi che non sono presenti in altri flussi. È consigliabile usare questo flusso solo quando i flussi più sicuri, ad esempio le identità gestite, non sono validi.
Ottenere la stringa di connessione dalla variabile di ambiente aggiunta da Service Connector.
using StackExchange.Redis;
var connectionString = Environment.GetEnvironmentVariable("AZURE_REDIS_CONNECTIONSTRING");
var _redisConnection = await RedisConnection.InitializeAsync(connectionString: connectionString);
Aggiungere la dipendenza seguente nel pom.xml file:
Ottenere la stringa di connessione dalla variabile di ambiente aggiunta da Service Connector.
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import java.net.URI;
String connectionString = System.getenv("AZURE_REDIS_CONNECTIONSTRING");
URI uri = new URI(connectionString);
JedisShardInfo shardInfo = new JedisShardInfo(uri);
shardInfo.setSsl(true);
Jedis jedis = new Jedis(shardInfo);
Per configurare l'applicazione Spring, vedere Usare Cache Redis di Azure in Spring. Service Connector aggiunge le proprietà di configurazione a Spring Apps.
Installare le dipendenze.
pip install redis
Ottenere la stringa di connessione dalla variabile di ambiente aggiunta da Service Connector.
Per altri linguaggi, è possibile usare le informazioni di connessione impostate da Service Connector sulle variabili di ambiente per connettersi a Cache di Azure per Redis.
Entità servizio
Nome variabile di ambiente predefinito
Descrizione
Valore di esempio
AZURE_REDIS_HOST
Endpoint Redis
<RedisName>.redis.cache.windows.net
AZURE_REDIS_CLIENTID
ID client dell'entità servizio
<client-ID>
AZURE_REDIS_CLIENTSECRET
Segreto dell'entità servizio
<client-secret>
AZURE_REDIS_TENANTID
ID tenant dell'entità servizio
<tenant-id>
Codice di esempio
I passaggi e il codice seguenti illustrano come usare un'entità servizio per connettersi a Redis.
Aggiungere la logica di autenticazione con le variabili di ambiente impostate da Service Connector. Per altre informazioni, vedere Estensione Microsoft.Azure.StackExchangeRedis.
using StackExchange.Redis;
var cacheHostName = Environment.GetEnvironmentVariable("AZURE_REDIS_HOST");
var configurationOptions = ConfigurationOptions.Parse($"{cacheHostName}:6380");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
// For user-assigned identity.
// var managedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// await configurationOptions.ConfigureForAzureWithUserAssignedManagedIdentityAsync(managedIdentityClientId);
// Service principal secret.
// var clientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// var tenantId = Environment.GetEnvironmentVariable("AZURE_REDIS_TENANTID");
// var secret = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTSECRET");
// await configurationOptions.ConfigureForAzureWithServicePrincipalAsync(clientId, tenantId, secret);
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
Aggiungere la dipendenza seguente nel pom.xml file:
Aggiungere la logica di autenticazione con le variabili di ambiente impostate da Service Connector. Per altre informazioni, vedere Azure-AAD-Authentication-With-Jedis.
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import java.net.URI;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
// For user-assigned identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().managedIdentityClientId(clientId).build();
// For AKS workload identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().workloadIdentityClientId(clientId).build();
// For service principal.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// String secret = System.getenv("AZURE_REDIS_CLIENTSECRET");
// String tenant = System.getenv("AZURE_REDIS_TENANTID");
// ClientSecretCredential defaultAzureCredential = new ClientSecretCredentialBuilder().tenantId(tenant).clientId(clientId).clientSecret(secret).build();
String token = defaultAzureCredential
.getToken(new TokenRequestContext()
.addScopes("https://redis.azure.com/.default")).block().getToken();
// SSL connection is required.
boolean useSsl = true;
// TODO: Replace Host Name with Azure Cache for Redis Host Name.
String username = extractUsernameFromToken(token);
String cacheHostname = System.getenv("AZURE_REDIS_HOST");
// Create Jedis client and connect to Azure Cache for Redis over the TLS/SSL port using the access token as password.
// Note, Redis Cache host name and port are required below.
Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
.password(token) // Microsoft Entra access token as password is required.
.user(username) // Username is Required
.ssl(useSsl) // SSL Connection is Required
.build());
// Set a value against your key in the Redis cache.
jedis.set("Az:key", "testValue");
System.out.println(jedis.get("Az:key"));
// Close the Jedis Client
jedis.close();
Non ancora supportato.
Installare le dipendenze.
pip install redis azure-identity
Aggiungere la logica di autenticazione con le variabili di ambiente impostate da Service Connector. Per altre informazioni, vedere azure-aad-auth-with-redis-py.
import os
import time
import logging
import redis
import base64
import json
from azure.identity import DefaultAzureCredential
host = os.getenv('AZURE_REDIS_HOST')
scope = "https://redis.azure.com/.default"
port = 6380 # Required
def extract_username_from_token(token):
parts = token.split('.')
base64_str = parts[1]
if len(base64_str) % 4 == 2:
base64_str += "=="
elif len(base64_str) % 4 == 3:
base64_str += "="
json_bytes = base64.b64decode(base64_str)
json_str = json_bytes.decode('utf-8')
jwt = json.loads(json_str)
return jwt['oid']
def re_authentication():
_LOGGER = logging.getLogger(__name__)
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For service principal.
# tenant_id = os.getenv("AZURE_TENANT_ID")
# client_id = os.getenv("AZURE_CLIENT_ID")
# client_secret = os.getenv("AZURE_CLIENT_SECRET")
# cred = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
token = cred.get_token(scope)
user_name = extract_username_from_token(token.token)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
max_retry = 3
for index in range(max_retry):
try:
if _need_refreshing(token):
_LOGGER.info("Refreshing token...")
tmp_token = cred.get_token(scope)
if tmp_token:
token = tmp_token
r.execute_command("AUTH", user_name, token.token)
r.set("Az:key1", "value1")
t = r.get("Az:key1")
print(t)
break
except redis.ConnectionError:
_LOGGER.info("Connection lost. Reconnecting.")
token = cred.get_token(scope)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
except Exception:
_LOGGER.info("Unknown failures.")
break
def _need_refreshing(token, refresh_offset=300):
return not token or token.expires_on - time.time() < refresh_offset
if __name__ == '__main__':
re_authentication()
import { createClient } from "redis";
import { DefaultAzureCredential } from "@azure/identity";
function extractUsernameFromToken(accessToken: AccessToken): string{
const base64Metadata = accessToken.token.split(".")[1];
const { oid } = JSON.parse(
Buffer.from(base64Metadata, "base64").toString("utf8"),
);
return oid;
}
async function main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_REDIS_TENANTID;
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const clientSecret = process.env.AZURE_REDIS_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
const redisScope = "https://redis.azure.com/.default";
let accessToken = await credential.getToken(redisScope);
console.log("access Token", accessToken);
const host = process.env.AZURE_REDIS_HOST;
// Create redis client and connect to Azure Cache for Redis over the TLS port using the access token as password.
const client = createClient({
username: extractUsernameFromToken(accessToken),
password: accessToken.token,
url: `redis://${host}:6380`,
pingInterval: 100000,
socket: {
tls: true,
keepAlive: 0
},
});
client.on("error", (err) => console.log("Redis Client Error", err));
await client.connect();
// Set a value against your key in Azure Redis Cache.
await client.set("Az:key", "value1312");
// Get value of your key in Azure Redis Cache.
console.log("value-", await client.get("Az:key"));
}
main().catch((err) => {
console.log("error code: ", err.code);
console.log("error message: ", err.message);
console.log("error stack: ", err.stack);
});
Per altre lingue, è possibile usare la libreria client di Azure Identity (e le informazioni di connessione impostate da Service Connector per le variabili di ambiente) per connettersi a cache di Azure per Redis.