Skip to content

Commit f41aa25

Browse files
authored
Update cache-nodejs-get-started.md
1 parent 357937d commit f41aa25

File tree

1 file changed

+119
-5
lines changed

1 file changed

+119
-5
lines changed

articles/azure-cache-for-redis/cache-nodejs-get-started.md

Lines changed: 119 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@ The [node-redis](https://github.com/redis/node-redis) library is the primary Nod
3030
npm install redis
3131
```
3232

33-
## [Microsoft EntraID Authentication (recommended)](#tab/entraid)
33+
## [Microsoft Entra ID Authentication (recommended)](#tab/entraid)
3434

35-
## Enable Microsoft EntraID and add a User or Service Principal
35+
## Enable Microsoft Entra ID and add a User or Service Principal
3636
<--Fran, we probably need an include file on enabling EntraID-->
3737
Blah blah blah, do the steps listed [here](cache-azure-active-directory-for-authentication)
3838

@@ -45,10 +45,17 @@ npm install @azure/identity
4545

4646
## Create a new Node.js app
4747

48+
1.Add environment variables for your **Host name** and **Service Principal ID**, which is the object ID your Entra ID service principal or user. In the Azure Portal, this is shown as the _Username_.
49+
50+
```cmd
51+
set AZURE_CACHE_FOR_REDIS_HOST_NAME=contosoCache
52+
set REDIS_SERVICE_PRINCIPAL_ID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
53+
```
54+
4855
1. Create a new script file named *redistest.js*.
4956
1. Add the following example JavaScript to the file.
5057

51-
```node
58+
```javascript
5259
const { createClient } = require("redis");
5360
const { DefaultAzureCredential } = require("@azure/identity");
5461

@@ -63,9 +70,9 @@ async function main() {
6370

6471
// Create redis client and connect to the Azure Cache for Redis over the TLS port using the access token as password.
6572
const cacheConnection = createClient({
66-
username: process.env.REDIS_SERVICE_PRINCIPAL_NAME,
73+
username: process.env.REDIS_SERVICE_PRINCIPAL_ID,
6774
password: accessToken.token,
68-
url: `redis://${process.env.REDIS_HOSTNAME}:6380`,
75+
url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,
6976
pingInterval: 100000,
7077
socket: {
7178
tls: true,
@@ -130,6 +137,113 @@ This code shows you how to connect to an Azure Cache for Redis instance using th
130137
Done
131138
```
132139

140+
## Create a sample javascript app with reauthentication
141+
Microsoft EntraID access tokens have limited lifespans, [averaging 75 minutes](../../entra/identity-platform/configurable-token-lifetimes#token-lifetime-policies-for-access-saml-and-id-tokens). In order to maintain a connection to your cache, you need to refresh the token. This example demonstrates how to do this using Javascript.
142+
143+
1. Create a new script file named *redistestreauth.js*.
144+
1. Add the following example JavaScript to the file.
145+
146+
```javascript
147+
const { createClient } = require("redis");
148+
const { DefaultAzureCredential } = require("@azure/identity");
149+
150+
async function returnPassword(credential) {
151+
const redisScope = "https://redis.azure.com/.default";
152+
153+
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
154+
return credential.getToken(redisScope);
155+
}
156+
157+
async function main() {
158+
// Construct a Token Credential from Identity library, e.g. ClientSecretCredential / ClientCertificateCredential / ManagedIdentityCredential, etc.
159+
const credential = new DefaultAzureCredential();
160+
let accessToken = await returnPassword(credential);
161+
162+
// Create redis client and connect to the Azure Cache for Redis over the TLS port using the access token as password.
163+
let cacheConnection = createClient({
164+
username: process.env.REDIS_SERVICE_PRINCIPAL_ID,
165+
password: accessToken.token,
166+
url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,
167+
pingInterval: 100000,
168+
socket: {
169+
tls: true,
170+
keepAlive: 0
171+
},
172+
});
173+
174+
cacheConnection.on("error", (err) => console.log("Redis Client Error", err));
175+
await cacheConnection.connect();
176+
177+
for (let i = 0; i < 3; i++) {
178+
try {
179+
// PING command
180+
console.log("\nCache command: PING");
181+
console.log("Cache response : " + await cacheConnection.ping());
182+
183+
// SET
184+
console.log("\nCache command: SET Message");
185+
console.log("Cache response : " + await cacheConnection.set("Message",
186+
"Hello! The cache is working from Node.js!"));
187+
188+
// GET
189+
console.log("\nCache command: GET Message");
190+
console.log("Cache response : " + await cacheConnection.get("Message"));
191+
192+
// Client list, useful to see if connection list is growing...
193+
console.log("\nCache command: CLIENT LIST");
194+
console.log("Cache response : " + await cacheConnection.sendCommand(["CLIENT", "LIST"]));
195+
break;
196+
} catch (e) {
197+
console.log("error during redis get", e.toString());
198+
if ((accessToken.expiresOnTimestamp <= Date.now())|| (redis.status === "end" || "close") ) {
199+
await redis.disconnect();
200+
accessToken = await returnPassword(credential);
201+
cacheConnection = createClient({
202+
username: process.env.REDIS_SERVICE_PRINCIPAL_ID,
203+
password: accessToken.token,
204+
url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,
205+
pingInterval: 100000,
206+
socket: {
207+
tls: true,
208+
keepAlive: 0
209+
},
210+
});
211+
}
212+
}
213+
}
214+
}
215+
216+
main().then((result) => console.log(result)).catch(ex => console.log(ex));
217+
```
218+
1. Run the script with Node.js.
219+
220+
```bash
221+
node redistestreauth.js
222+
```
223+
224+
1. Example the output.
225+
226+
```console
227+
Cache command: PING
228+
Cache response : PONG
229+
230+
Cache command: GET Message
231+
Cache response : Hello! The cache is working from Node.js!
232+
233+
Cache command: SET Message
234+
Cache response : OK
235+
236+
Cache command: GET Message
237+
Cache response : Hello! The cache is working from Node.js!
238+
239+
Cache command: CLIENT LIST
240+
Cache response : id=10017364 addr=76.22.73.183:59380 fd=221 name= age=1 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 argv-mem=10 obl=0 oll=0 omem=0 tot-mem=61466 ow=0 owmem=0 events=r cmd=client user=default numops=6
241+
```
242+
>[!NOTE]
243+
>For additional examples of using Microsoft Entra ID to authenticate to Redis using the node-redis library, please see [this GitHub repo](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureCacheForRedis/node-redis.md)
244+
>
245+
246+
133247
## [Access Key Authentication](#tab/accesskey)
134248
135249
[!INCLUDE [redis-cache-access-keys](includes/redis-cache-access-keys.md)]

0 commit comments

Comments
 (0)