Go と Java - Spring Boot を除くすべてのクライアントの種類では、Service Connector を使用して Azure Cache for Redis に接続するために、テーブルで参照されている任意の認証方法を使用できます。 Go と Java - Spring Boot でサポートされている認証方法は、シークレット/接続文字列またはサービス プリンシパルのみです。
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);
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();
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);
});
他の言語の場合は、Azure ID クライアント ライブラリ (および Service Connector が環境変数に設定する接続情報) を使って、Azure Cache for Redis に接続できます。
ユーザー割り当てマネージド ID
既定の環境変数名
説明
サンプルの値
AZURE_REDIS_HOST
Redis エンドポイント
<RedisName>.redis.cache.windows.net
AZURE_REDIS_CLIENTID
マネージド ID のクライアント ID
<client-ID>
サンプル コード
次の手順とコードは、ユーザー割り当てマネージド ID を使って Redis に接続する方法を示しています。
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);
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();
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);
});
他の言語の場合は、Azure ID クライアント ライブラリ (および Service Connector が環境変数に設定する接続情報) を使って、Azure Cache for Redis に接続できます。
接続文字列
警告
使用可能な最も安全な認証フローを使用することをお勧めします。 ここで示される認証フローでは、アプリケーションで非常に高い信頼度が要求されるため、他のフローには存在しないリスクが伴います。 このフローは、マネージド ID など、より安全なフローが実行可能ではない場合にのみ使用してください。
using StackExchange.Redis;
var connectionString = Environment.GetEnvironmentVariable("AZURE_REDIS_CONNECTIONSTRING");
var _redisConnection = await RedisConnection.InitializeAsync(connectionString: connectionString);
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);
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();
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);
});
他の言語の場合は、Azure ID クライアント ライブラリ (および Service Connector が環境変数に設定する接続情報) を使って、Azure Cache for Redis に接続できます。