Skip to content

Commit 3dabfa1

Browse files
committed
Refined PM content
1 parent c2b4271 commit 3dabfa1

File tree

1 file changed

+137
-19
lines changed

1 file changed

+137
-19
lines changed

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

Lines changed: 137 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -17,38 +17,47 @@ In this quickstart, you incorporate Azure Cache for Redis into a Node.js app to
1717
## Prerequisites
1818

1919
- Azure subscription - [create one for free](https://azure.microsoft.com/free/)
20-
- Node.js installed, if you haven't done so already. See [Install Node.js on Windows](../../windows/dev-environment/javascript/nodejs-on-windows) for instructions on how to install Node and NPM on a Windows machine.
20+
- Node.js installed, if you haven't done so already. See [Install Node.js on Windows](/windows/dev-environment/javascript/nodejs-on-windows) for instructions on how to install Node and Node Package Manager (NPM) on a Windows computer.
2121

2222
## Create a cache
2323

2424
[!INCLUDE [redis-cache-create](~/reusable-content/ce-skilling/azure/includes/azure-cache-for-redis/includes/redis-cache-create.md)]
2525

26-
## Install the node-redis client lbirary
26+
## Install the node-redis client library
27+
2728
The [node-redis](https://github.com/redis/node-redis) library is the primary Node.js client for Redis. You can install the client with [npm](https://docs.npmjs.com/about-npm) by using the following command:
2829

2930
```bash
3031
npm install redis
3132
```
3233

33-
## [Microsoft EntraID Authentication (recommended)](#tab/entraid)
34+
## [Microsoft Entra ID Authentication (recommended)](#tab/entraid)
35+
36+
### Enable Microsoft Entra ID and add a User or Service Principal
37+
38+
[!INCLUDE cache-entra-access]
3439

35-
## Enable Microsoft EntraID and add a User or Service Principal
36-
<--Fran, we probably need an include file on enabling EntraID-->
37-
Blah blah blah, do the steps listed [here](cache-azure-active-directory-for-authentication)
40+
### Install the JavaScript Azure Identity client library
3841

39-
## Install the JavaScript Azure Identity client library
40-
The [Microsoft Authentication Library (MSAL)](../../entra/identity-platform/msal-overview) allows you to acquire security tokens from Microsoft identity to authenticate users. There's a [Javascript Azure identity client library](../../javascript/api/overview/azure/identity-readme) available that uses MSAL to provide token authentication support. Install this library using `npm`:
42+
The [Microsoft Authentication Library (MSAL)](/entra/identity-platform/msal-overview) allows you to acquire security tokens from Microsoft identity to authenticate users. There's a [JavaScript Azure identity client library](/javascript/api/overview/azure/identity-readme) available that uses MSAL to provide token authentication support. Install this library using `npm`:
4143

4244
```bash
4345
npm install @azure/identity
4446
```
4547

46-
## Create a new Node.js app
48+
### Create a new Node.js app using Microsoft Entra ID
49+
50+
1.Add environment variables for your **Host name** and **Service Principal ID**, which is the object ID your Microsoft Entra ID service principal or user. In the Azure portal, this is shown as the _Username_.
4751

48-
1. Create a new script file named *redistest.js*.
52+
```cmd
53+
set AZURE_CACHE_FOR_REDIS_HOST_NAME=contosoCache
54+
set REDIS_SERVICE_PRINCIPAL_ID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
55+
```
56+
57+
1. Create a new script file named _redistest.js_.
4958
1. Add the following example JavaScript to the file.
50-
51-
```node
59+
60+
```javascript
5261
const { createClient } = require("redis");
5362
const { DefaultAzureCredential } = require("@azure/identity");
5463

@@ -63,9 +72,9 @@ async function main() {
6372

6473
// Create redis client and connect to the Azure Cache for Redis over the TLS port using the access token as password.
6574
const cacheConnection = createClient({
66-
username: process.env.REDIS_SERVICE_PRINCIPAL_NAME,
75+
username: process.env.REDIS_SERVICE_PRINCIPAL_ID,
6776
password: accessToken.token,
68-
url: `redis://${process.env.REDIS_HOSTNAME}:6380`,
77+
url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,
6978
pingInterval: 100000,
7079
socket: {
7180
tls: true,
@@ -130,6 +139,115 @@ This code shows you how to connect to an Azure Cache for Redis instance using th
130139
Done
131140
```
132141

142+
## Create a sample JavaScript app with reauthentication
143+
144+
Microsoft Entra ID access tokens have a limited lifespan, [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.
145+
146+
1. Create a new script file named _redistestreauth.js_.
147+
1. Add the following example JavaScript to the file.
148+
149+
```javascript
150+
const { createClient } = require("redis");
151+
const { DefaultAzureCredential } = require("@azure/identity");
152+
153+
async function returnPassword(credential) {
154+
const redisScope = "https://redis.azure.com/.default";
155+
156+
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
157+
return credential.getToken(redisScope);
158+
}
159+
160+
async function main() {
161+
// Construct a Token Credential from Identity library, e.g. ClientSecretCredential / ClientCertificateCredential / ManagedIdentityCredential, etc.
162+
const credential = new DefaultAzureCredential();
163+
let accessToken = await returnPassword(credential);
164+
165+
// Create redis client and connect to the Azure Cache for Redis over the TLS port using the access token as password.
166+
let cacheConnection = createClient({
167+
username: process.env.REDIS_SERVICE_PRINCIPAL_ID,
168+
password: accessToken.token,
169+
url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,
170+
pingInterval: 100000,
171+
socket: {
172+
tls: true,
173+
keepAlive: 0
174+
},
175+
});
176+
177+
cacheConnection.on("error", (err) => console.log("Redis Client Error", err));
178+
await cacheConnection.connect();
179+
180+
for (let i = 0; i < 3; i++) {
181+
try {
182+
// PING command
183+
console.log("\nCache command: PING");
184+
console.log("Cache response : " + await cacheConnection.ping());
185+
186+
// SET
187+
console.log("\nCache command: SET Message");
188+
console.log("Cache response : " + await cacheConnection.set("Message",
189+
"Hello! The cache is working from Node.js!"));
190+
191+
// GET
192+
console.log("\nCache command: GET Message");
193+
console.log("Cache response : " + await cacheConnection.get("Message"));
194+
195+
// Client list, useful to see if connection list is growing...
196+
console.log("\nCache command: CLIENT LIST");
197+
console.log("Cache response : " + await cacheConnection.sendCommand(["CLIENT", "LIST"]));
198+
break;
199+
} catch (e) {
200+
console.log("error during redis get", e.toString());
201+
if ((accessToken.expiresOnTimestamp <= Date.now())|| (redis.status === "end" || "close") ) {
202+
await redis.disconnect();
203+
accessToken = await returnPassword(credential);
204+
cacheConnection = createClient({
205+
username: process.env.REDIS_SERVICE_PRINCIPAL_ID,
206+
password: accessToken.token,
207+
url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,
208+
pingInterval: 100000,
209+
socket: {
210+
tls: true,
211+
keepAlive: 0
212+
},
213+
});
214+
}
215+
}
216+
}
217+
}
218+
219+
main().then((result) => console.log(result)).catch(ex => console.log(ex));
220+
```
221+
222+
1. Run the script with Node.js.
223+
224+
```bash
225+
node redistestreauth.js
226+
```
227+
228+
1. Example the output.
229+
230+
```console
231+
Cache command: PING
232+
Cache response : PONG
233+
234+
Cache command: GET Message
235+
Cache response : Hello! The cache is working from Node.js!
236+
237+
Cache command: SET Message
238+
Cache response : OK
239+
240+
Cache command: GET Message
241+
Cache response : Hello! The cache is working from Node.js!
242+
243+
Cache command: CLIENT LIST
244+
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
245+
```
246+
247+
>[!NOTE]
248+
>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)
249+
>
250+
133251
## [Access Key Authentication](#tab/accesskey)
134252
135253
[!INCLUDE [redis-cache-access-keys](includes/redis-cache-access-keys.md)]
@@ -149,7 +267,7 @@ set AZURE_CACHE_FOR_REDIS_ACCESS_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
149267
150268
## Create a new Node.js app
151269
152-
1. Create a new script file named *redistest.js*.
270+
1. Create a new script file named _redistest.js_.
153271
1. Add the following example JavaScript to the file.
154272
155273
```javascript
@@ -232,6 +350,7 @@ set AZURE_CACHE_FOR_REDIS_ACCESS_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
232350
233351
Done
234352
```
353+
235354
---
236355
237356
## Clean up resources
@@ -244,7 +363,7 @@ If you continue to the next tutorial, can keep the resources created in this qui
244363
245364
1. Sign in to the [Azure portal](https://portal.azure.com) and select **Resource groups**.
246365
247-
1. In the **Filter by name** text box, enter the name of your resource group. The instructions for this article used a resource group named *TestResources*. On your resource group in the result list, select **...** then **Delete resource group**.
366+
1. In the **Filter by name** text box, enter the name of your resource group. The instructions for this article used a resource group named _TestResources_. On your resource group in the result list, select **...** then **Delete resource group**.
248367
249368
![Delete Azure Resource group](./media/cache-nodejs-get-started/redis-cache-delete-resource-group.png)
250369
@@ -256,9 +375,8 @@ If you continue to the next tutorial, can keep the resources created in this qui
256375
257376
Get the [Node.js quickstart](https://github.com/Azure-Samples/azure-cache-redis-samples/tree/main/quickstart/nodejs) on GitHub.
258377
259-
## Next steps
378+
## Related content
260379
261380
In this quickstart, you learned how to use Azure Cache for Redis from a Node.js application. Continue to the next quickstart to use Azure Cache for Redis with an ASP.NET web app.
262381
263-
> [!div class="nextstepaction"]
264-
> [Create an ASP.NET web app that uses an Azure Cache for Redis.](./cache-web-app-howto.md)
382+
- [Create an ASP.NET web app that uses an Azure Cache for Redis.](./cache-web-app-howto.md)

0 commit comments

Comments
 (0)