Skip to content

Commit 82f43c2

Browse files
committed
Replace Azure Identity code samples for Redis
1 parent f678cb3 commit 82f43c2

File tree

2 files changed

+15
-242
lines changed

2 files changed

+15
-242
lines changed

articles/service-connector/how-to-integrate-redis-cache.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ author: maud-lv
55
ms.author: malev
66
ms.service: service-connector
77
ms.topic: how-to
8-
ms.date: 03/14/2025
8+
ms.date: 07/23/2025
99
---
1010

1111
# Integrate Azure Cache for Redis with Service Connector
1212

13-
This article covers supported authentication methods, clients, and sample code you can use to connect your apps to Azure Cache for Redis using Service Connector.In this article, you'll also find default environment variable names, values, and configuration obtained when creating service connections.
13+
This article covers supported authentication methods, clients, and sample code you can use to connect your apps to Azure Cache for Redis using Service Connector. In this article, you'll also find default environment variable names, values, and configuration obtained when creating service connections.
1414

1515
## Supported compute services
1616

@@ -28,13 +28,13 @@ The following table shows which combinations of authentication methods and clien
2828

2929
| Client type | System-assigned managed identity | User-assigned managed identity | Secret / connection string | Service principal |
3030
|--------------------|----------------------------------|--------------------------------|----------------------------|-------------------|
31-
| .NET | Yes | Yes | Yes | Yes |
32-
| Go | No | No | Yes | No |
33-
| Java | Yes | Yes | Yes | Yes |
31+
| .NET | Yes | Yes | Yes | Yes |
32+
| Go | Yes | Yes | Yes | Yes |
33+
| Java | Yes | Yes | Yes | Yes |
3434
| Java - Spring Boot | No | No | Yes | No |
35-
| Node.js | Yes | Yes | Yes | Yes |
36-
| Python | Yes | Yes | Yes | Yes |
37-
| None | Yes | Yes | Yes | Yes |
35+
| Node.js | Yes | Yes | Yes | Yes |
36+
| Python | Yes | Yes | Yes | Yes |
37+
| None | Yes | Yes | Yes | Yes |
3838

3939
## Default environment variable names or application properties and sample code
4040

articles/service-connector/includes/code-redis-me-id.md

Lines changed: 7 additions & 234 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ author: xfz11
33
description: Code example
44
ms.service: service-connector
55
ms.topic: include
6-
ms.date: 1/2/2025
6+
ms.date: 07/23/2025
77
ms.author: xiaofanzhou
88
---
99

@@ -42,250 +42,23 @@ ms.author: xiaofanzhou
4242
4343
#### [Java](#tab/java)
4444
45-
1. Add the following dependency in your `pom.xml` file:
45+
Follow the instructions at [Connect to Azure Managed Redis](https://redis.io/docs/latest/develop/clients/jedis/amr/) for using the `redis-authx-entraid` package.
4646
47-
```xml
48-
<dependency>
49-
<groupId>com.azure</groupId>
50-
<artifactId>azure-identity</artifactId>
51-
<version>1.11.2</version> <!-- {x-version-update;com.azure:azure-identity;dependency} -->
52-
</dependency>
53-
54-
<dependency>
55-
<groupId>redis.clients</groupId>
56-
<artifactId>jedis</artifactId>
57-
<version>5.1.0</version> <!-- {x-version-update;redis.clients:jedis;external_dependency} -->
58-
</dependency>
59-
```
60-
61-
1. Add the authentication logic with environment variables set by Service Connector. For more information, see [Azure-AAD-Authentication-With-Jedis](https://aka.ms/redis/aad/sample-code/java-jedis).
62-
63-
```java
64-
import redis.clients.jedis.DefaultJedisClientConfig;
65-
import redis.clients.jedis.Jedis;
66-
import redis.clients.jedis.JedisShardInfo;
67-
import java.net.URI;
68-
69-
// Uncomment the following lines corresponding to the authentication type you want to use.
70-
// For system-assigned identity.
71-
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
72-
73-
// For user-assigned identity.
74-
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
75-
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().managedIdentityClientId(clientId).build();
76-
77-
// For AKS workload identity.
78-
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
79-
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().workloadIdentityClientId(clientId).build();
80-
81-
// For service principal.
82-
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
83-
// String secret = System.getenv("AZURE_REDIS_CLIENTSECRET");
84-
// String tenant = System.getenv("AZURE_REDIS_TENANTID");
85-
// ClientSecretCredential defaultAzureCredential = new ClientSecretCredentialBuilder().tenantId(tenant).clientId(clientId).clientSecret(secret).build();
86-
87-
String token = defaultAzureCredential
88-
.getToken(new TokenRequestContext()
89-
.addScopes("https://redis.azure.com/.default")).block().getToken();
90-
91-
// SSL connection is required.
92-
boolean useSsl = true;
93-
// TODO: Replace Host Name with Azure Cache for Redis Host Name.
94-
String username = extractUsernameFromToken(token);
95-
String cacheHostname = System.getenv("AZURE_REDIS_HOST");
96-
97-
// Create Jedis client and connect to Azure Cache for Redis over the TLS/SSL port using the access token as password.
98-
// Note, Redis Cache host name and port are required below.
99-
Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
100-
.password(token) // Microsoft Entra access token as password is required.
101-
.user(username) // Username is Required
102-
.ssl(useSsl) // SSL Connection is Required
103-
.build());
104-
105-
// Set a value against your key in the Redis cache.
106-
jedis.set("Az:key", "testValue");
107-
System.out.println(jedis.get("Az:key"));
108-
109-
// Close the Jedis Client
110-
jedis.close();
111-
```
11247
#### [Spring Boot](#tab/springBoot)
48+
11349
Not supported yet.
11450
11551
#### [Python](#tab/python)
11652
117-
1. Install dependencies.
118-
119-
```bash
120-
pip install redis azure-identity
121-
```
122-
123-
1. Add the authentication logic with environment variables set by Service Connector. For more information, see [azure-aad-auth-with-redis-py](https://aka.ms/redis/aad/sample-code/python).
124-
125-
```python
126-
import os
127-
import time
128-
import logging
129-
import redis
130-
import base64
131-
import json
132-
from azure.identity import DefaultAzureCredential
133-
134-
host = os.getenv('AZURE_REDIS_HOST')
135-
scope = "https://redis.azure.com/.default"
136-
port = 6380 # Required
137-
138-
def extract_username_from_token(token):
139-
parts = token.split('.')
140-
base64_str = parts[1]
141-
142-
if len(base64_str) % 4 == 2:
143-
base64_str += "=="
144-
elif len(base64_str) % 4 == 3:
145-
base64_str += "="
146-
147-
json_bytes = base64.b64decode(base64_str)
148-
json_str = json_bytes.decode('utf-8')
149-
jwt = json.loads(json_str)
150-
151-
return jwt['oid']
152-
153-
def re_authentication():
154-
_LOGGER = logging.getLogger(__name__)
155-
# Uncomment the following lines corresponding to the authentication type you want to use.
156-
# For system-assigned identity.
157-
# cred = DefaultAzureCredential()
158-
159-
# For user-assigned identity.
160-
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
161-
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
162-
163-
# For user-assigned identity.
164-
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
165-
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
166-
167-
# For service principal.
168-
# tenant_id = os.getenv("AZURE_TENANT_ID")
169-
# client_id = os.getenv("AZURE_CLIENT_ID")
170-
# client_secret = os.getenv("AZURE_CLIENT_SECRET")
171-
# cred = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
172-
173-
token = cred.get_token(scope)
174-
user_name = extract_username_from_token(token.token)
175-
r = redis.Redis(host=host,
176-
port=port,
177-
ssl=True, # ssl connection is required.
178-
username=user_name,
179-
password=token.token,
180-
decode_responses=True)
181-
max_retry = 3
182-
for index in range(max_retry):
183-
try:
184-
if _need_refreshing(token):
185-
_LOGGER.info("Refreshing token...")
186-
tmp_token = cred.get_token(scope)
187-
if tmp_token:
188-
token = tmp_token
189-
r.execute_command("AUTH", user_name, token.token)
190-
r.set("Az:key1", "value1")
191-
t = r.get("Az:key1")
192-
print(t)
193-
break
194-
except redis.ConnectionError:
195-
_LOGGER.info("Connection lost. Reconnecting.")
196-
token = cred.get_token(scope)
197-
r = redis.Redis(host=host,
198-
port=port,
199-
ssl=True, # ssl connection is required.
200-
username=user_name,
201-
password=token.token,
202-
decode_responses=True)
203-
except Exception:
204-
_LOGGER.info("Unknown failures.")
205-
break
206-
207-
208-
def _need_refreshing(token, refresh_offset=300):
209-
return not token or token.expires_on - time.time() < refresh_offset
210-
211-
if __name__ == '__main__':
212-
re_authentication()
213-
```
53+
Follow the instructions at [Connect to Azure Managed Redis](https://redis.io/docs/latest/develop/clients/redis-py/amr/) for using the `redis-entra-id` package.
21454
21555
#### [Go](#tab/go)
216-
Not supported yet.
21756
218-
#### [Node.js](#tab/nodejs)
219-
220-
1. Install dependencies.
57+
Follow the instructions at [Connect to Azure Managed Redis](https://redis.io/docs/latest/develop/clients/go/amr/) for using the `go-redis-entraid` package.
22158
222-
```bash
223-
npm install redis @azure/identity
224-
```
225-
226-
1. Add the authentication logic with environment variables set by Service Connector. For more information, see [Azure Cache for Redis: Microsoft Entra ID with node-redis client library](https://aka.ms/redis/aad/sample-code/js-noderedis).
227-
228-
```javascript
229-
import { createClient } from "redis";
230-
import { DefaultAzureCredential } from "@azure/identity";
231-
232-
function extractUsernameFromToken(accessToken: AccessToken): string{
233-
const base64Metadata = accessToken.token.split(".")[1];
234-
const { oid } = JSON.parse(
235-
Buffer.from(base64Metadata, "base64").toString("utf8"),
236-
);
237-
return oid;
238-
}
239-
240-
async function main() {
241-
// Uncomment the following lines corresponding to the authentication type you want to use.
242-
// For system-assigned identity.
243-
// const credential = new DefaultAzureCredential();
244-
245-
// For user-assigned identity.
246-
// const clientId = process.env.AZURE_REDIS_CLIENTID;
247-
// const credential = new DefaultAzureCredential({
248-
// managedIdentityClientId: clientId
249-
// });
250-
251-
// For service principal.
252-
// const tenantId = process.env.AZURE_REDIS_TENANTID;
253-
// const clientId = process.env.AZURE_REDIS_CLIENTID;
254-
// const clientSecret = process.env.AZURE_REDIS_CLIENTSECRET;
255-
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
256-
257-
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
258-
const redisScope = "https://redis.azure.com/.default";
259-
let accessToken = await credential.getToken(redisScope);
260-
console.log("access Token", accessToken);
261-
const host = process.env.AZURE_REDIS_HOST;
262-
263-
// Create redis client and connect to Azure Cache for Redis over the TLS port using the access token as password.
264-
const client = createClient({
265-
username: extractUsernameFromToken(accessToken),
266-
password: accessToken.token,
267-
url: `redis://${host}:6380`,
268-
pingInterval: 100000,
269-
socket: {
270-
tls: true,
271-
keepAlive: 0
272-
},
273-
});
274-
275-
client.on("error", (err) => console.log("Redis Client Error", err));
276-
await client.connect();
277-
// Set a value against your key in Azure Redis Cache.
278-
await client.set("Az:key", "value1312");
279-
// Get value of your key in Azure Redis Cache.
280-
console.log("value-", await client.get("Az:key"));
281-
}
59+
#### [Node.js](#tab/nodejs)
28260
283-
main().catch((err) => {
284-
console.log("error code: ", err.code);
285-
console.log("error message: ", err.message);
286-
console.log("error stack: ", err.stack);
287-
});
288-
```
61+
Follow the instructions at [Connect to Azure Managed Redis](https://redis.io/docs/latest/develop/clients/nodejs/amr/) for using the `@redis/entraid` package.
28962
29063
### [Other](#tab/other)
29164

0 commit comments

Comments
 (0)