Skip to content

Commit 28e44d3

Browse files
navzamcompulimcorinagum
authored
Add sample for using Direct Line tokens (#3779)
* Add initial code for direct-line-token sample * Add README to new direct-line-token sample * Fix indentation issues * Clarify FAQ in direct-line-token sample README * Add direct-line-token sample to samples README * Update CHANGELOG for direct-line-token sample * Move JS code into separate javascript folder * Add C# bot for direct-line-token sample * Add C# API for direct-line-token-sample * Update direct-line-token sample README for C# * Clarify README in direct-line-token sample * In dl-token sample, separate dl API code * Remove CI badge from top of dl-token sample README * Apply suggestions from code review Co-authored-by: William Wong <compulim@users.noreply.github.com> Co-authored-by: Corina <14900841+corinagum@users.noreply.github.com>
1 parent 133193f commit 28e44d3

38 files changed

+3767
-1
lines changed

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
186186

187187
### Samples
188188

189-
- Fixes [#3632](https://github.com/microsoft/BotFramework-WebChat/issues/3632). Update reaction button sample: Add `replyToId` to the `postActivity` object, by [@amal-khalaf](https://github.com/amal-khalaf) in PR [#3769](https://github.com/microsoft/BotFramework-WebChat/pull/3769)
189+
- Fixes [#3632](https://github.com/microsoft/BotFramework-WebChat/issues/3632). Update reaction button sample : Add replyToId to the postActivity object, by [@amal-khalaf](https://github.com/amal-khalaf) in PR [#3769](https://github.com/microsoft/BotFramework-WebChat/pull/3769)
190+
- Fixes [#2343](https://github.com/microsoft/BotFramework-WebChat/issues/2343). Add sample for Direct Line tokens, by [@navzam](https://github.com/navzam), in PR [#3779](https://github.com/microsoft/BotFramework-WebChat/pull/3779)
190191

191192
## [4.12.0] - 2021-03-01
192193

Lines changed: 341 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,341 @@
1+
# Direct Line Token Sample
2+
3+
# Description
4+
5+
This sample demonstrates how to integrate Web Chat in a way that 1) does not expose your Direct Line secret to the browser, and 2) mitigates user impersonation by not allowing the client to set its own user ID.
6+
7+
See the [Motivation](#Motivation) section below for more background on these issues.
8+
9+
# Test out the hosted sample
10+
11+
There is no hosted demo for this sample yet.
12+
13+
# How to run locally
14+
15+
This demo includes a bot that you will run locally, so before running the code, you will have to set up an Azure Bot Service resource.
16+
17+
1. [Clone the code](#clone-the-code)
18+
1. [Setup Azure Bot Services](#setup-azure-bot-services)
19+
1. [Prepare and run the code](#prepare-and-run-the-code)
20+
21+
## Clone the code
22+
23+
To host this demo, you will need to clone the code and run locally.
24+
25+
<details><summary>Clone the JavaScript project</summary>
26+
27+
1. Clone this repository
28+
1. Create two empty files for environment variables, `/bot/.env` and `/web/.env`
29+
30+
</details>
31+
32+
<details><summary>Clone the C# project</summary>
33+
34+
1. Clone this repository
35+
1. Open the two `appsettings.json` files at `/bot/appsettings.json` and `/web/appsettings.json`
36+
37+
</details>
38+
39+
## Setup Azure Bot Services
40+
41+
> We prefer to use [Bot Channel Registration](https://ms.portal.azure.com/#create/Microsoft.BotServiceConnectivityGalleryPackage) during development. This will help you diagnose problems locally without deploying to the server and speed up development.
42+
43+
You can follow our instructions on how to [setup a new Bot Channel Registration](https://docs.microsoft.com/en-us/azure/bot-service/bot-service-quickstart-registration?view=azure-bot-service-3.0). Then save the resulting IDs/secrets into the appropriate local environment files, depending on your language:
44+
45+
<details><summary>JavaScript</summary>
46+
47+
1. Save the Microsoft App ID and password to `/bot/.env`
48+
- `MICROSOFT_APP_ID=12345678-1234-5678-abcd-12345678abcd`
49+
- `MICROSOFT_APP_PASSWORD=a1b2c3d4e5f6`
50+
1. Save the Web Chat secret to `/web/.env`
51+
- `DIRECT_LINE_SECRET=a1b2c3.d4e5f6g7h8i9j0`
52+
53+
</details>
54+
55+
<details><summary>C#</summary>
56+
57+
1. Save the Microsoft App ID and password to `/bot/appsettings.json`
58+
- `"MicrosoftAppId": "12345678-1234-5678-abcd-12345678abcd"`
59+
- `"MicrosoftAppPassword": "a1b2c3d4e5f6"`
60+
1. Save the Web Chat secret to `/web/appsettings.json`
61+
- `"DirectLineSecret": "a1b2c3.d4e5f6g7h8i9j0"`
62+
63+
</details>
64+
65+
During development, you will run your bot locally. Azure Bot Services will send activities to your bot thru a public URL. You can use [ngrok](https://ngrok.com/) to expose your bot server on a public URL.
66+
67+
1. Run `ngrok http -host-header=localhost:3978 3978`
68+
1. Update your Bot Channel Registration. You can use [Azure CLI](https://aka.ms/az-cli) or [Azure Portal](https://portal.azure.com)
69+
- Via Azure CLI
70+
- Run `az bot update --resource-group <your-bot-rg> --name <your-bot-name> --subscription <your-subscription-id> --endpoint "https://a1b2c3d4.ngrok.io/api/messages"`
71+
- Via Azure Portal
72+
- Browse to your Bot Channel Registration
73+
- Select "Settings"
74+
- In "Configuration" section, set "Messaging Endpoint" to `https://a1b2c3d4.ngrok.io/api/messages`
75+
76+
## Prepare and run the code
77+
78+
1. Under each of `bot`, and `web` folder, run the following commands, depending on your language:
79+
80+
<details><summary>JavaScript</summary>
81+
82+
1. `npm install`
83+
1. `npm start`
84+
85+
</details>
86+
87+
<details><summary>C#</summary>
88+
89+
1. `dotnet build`
90+
1. `dotnet run`
91+
92+
</details>
93+
94+
1. Browse to http://localhost:5000/ to start the demo
95+
96+
# Things to try out
97+
98+
- Type anything to the bot. It should reply with your user ID, which will stay the same for the duration of the session.
99+
- Open a new browser tab to http://localhost:5000 and type anything to the bot. It should reply with a different user ID since it has generated a different Direct Line token.
100+
101+
# Code
102+
103+
The code is organized into two separate folders:
104+
105+
- `/bot/` is the bot server
106+
- `/web/` is the REST API for generating Direct Line tokens
107+
- `GET /api/directline/token` will generate a new Direct Line token for the app. The token will be bound to a random user ID.
108+
- During development-time, it will also serve the bot server via `/api/messages/`
109+
- To enable this feature, add `PROXY_BOT_URL=http://localhost:3978` to `/web/.env`
110+
111+
## Constructing the user ID
112+
113+
In this sample, the user is anonymous, so the API randomly generates a user ID:
114+
115+
<details><summary>JavaScript</summary>
116+
117+
```js
118+
// web/src/routes/directLine/token.js
119+
120+
async function generateRandomUserId() {
121+
const buffer = await randomBytesAsync(16);
122+
return `dl_${buffer.toString('hex')}`;
123+
}
124+
```
125+
126+
</details>
127+
128+
<details><summary>C#</summary>
129+
130+
```csharp
131+
// web/Controllers/DirectLineController.cs
132+
133+
private static string GenerateRandomUserId()
134+
{
135+
byte[] tokenData = new byte[16];
136+
using var rng = new RNGCryptoServiceProvider();
137+
rng.GetBytes(tokenData);
138+
139+
return $"dl_{BitConverter.ToString(tokenData).Replace("-", "").ToLower()}";
140+
}
141+
```
142+
143+
</details>
144+
145+
The user ID is prefixed with "dl_" as required by the [Direct Line token API](https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication?view=azure-bot-service-4.0#generate-token).
146+
147+
## Retrieving a user-specific Direct Line token
148+
149+
The backend API calls the Direct Line API to retrieve a Direct Line token. Notice that we pass the user ID in the body of the request:
150+
151+
<details><summary>JavaScript</summary>
152+
153+
```js
154+
// web/src/generateDirectLineToken.js
155+
156+
async function generateDirectLineToken(secret, userId) {
157+
const { token } = await fetchJSON('https://directline.botframework.com/v3/directline/tokens/generate', {
158+
headers: {
159+
authorization: `Bearer ${secret}`,
160+
'Content-Type': 'application/json'
161+
},
162+
method: 'POST',
163+
body: JSON.stringify({
164+
user: {
165+
id: userId
166+
}
167+
})
168+
});
169+
170+
return token;
171+
};
172+
```
173+
174+
</details>
175+
176+
<details><summary>C#</summary>
177+
178+
```csharp
179+
// web/Services/DirectLineService.cs
180+
181+
httpClient.BaseAddress = new Uri("https://directline.botframework.com/");
182+
183+
...
184+
185+
public async Task<DirectLineTokenDetails> GetTokenAsync(string directLineSecret, string userId, CancellationToken cancellationToken = default)
186+
{
187+
var tokenRequestBody = new { user = new { id = userId } };
188+
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, "v3/directline/tokens/generate")
189+
{
190+
Headers =
191+
{
192+
{ "Authorization", $"Bearer {directLineSecret}" },
193+
},
194+
Content = new StringContent(JsonSerializer.Serialize(tokenRequestBody), Encoding.UTF8, MediaTypeNames.Application.Json),
195+
};
196+
197+
var tokenResponseMessage = await _httpClient.SendAsync(tokenRequest, cancellationToken);
198+
199+
...
200+
201+
using var responseContentStream = await tokenResponseMessage.Content.ReadAsStreamAsync();
202+
var tokenResponse = await JsonSerializer.DeserializeAsync<DirectLineTokenApiResponse>(responseContentStream);
203+
204+
return new DirectLineTokenDetails
205+
{
206+
Token = tokenResponse.Token,
207+
ConversationId = tokenResponse.ConversationId,
208+
ExpiresIn = tokenResponse.ExpiresIn,
209+
};
210+
}
211+
```
212+
213+
</details>
214+
215+
The resulting Direct Line token will be bound to the passed user ID.
216+
217+
## Calling the API and rendering Web Chat
218+
219+
The client-side page calls the API and uses the resulting Direct Line token to render Web Chat:
220+
221+
```js
222+
// public/index.html
223+
224+
const { token } = await fetchJSON('/api/directline/token');
225+
226+
WebChat.renderWebChat(
227+
{
228+
directLine: WebChat.createDirectLine({ token }),
229+
styleOptions: {
230+
backgroundColor: 'rgba(255, 255, 255, .8)'
231+
}
232+
},
233+
document.getElementById('webchat')
234+
);
235+
```
236+
237+
Note that we do *not* specify a user ID when initiating Web Chat. Direct Line will handle sending the user ID to the bot based on the token.
238+
239+
# Overview
240+
241+
This sample includes multiple parts:
242+
243+
- **The UI** is a static HTML/JS web page with Web Chat integrated via JavaScript bundle. It makes a POST request to the backend API and uses the resulting Direct Line token to render Web Chat.
244+
- **The backend API** generates Direct Line tokens. Each generated token is bound to a new, randomly-generated user ID.
245+
- **The bot** is a bare-bones bot that responds to every message by sending the user's ID.
246+
247+
## Motivation
248+
249+
### Hiding the Web Chat secret
250+
251+
When embedding Web Chat into a site, you must provide either your Direct Line secret or a Direct Line token so that Web Chat can communicate with the bot. The Direct Line secret can be used to access all of the bot's conversations, and it doesn't expire. A Direct Line token can only be used to access a single conversation, and it does expire. See the [Direct Line Authentication documentation](https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication?view=azure-bot-service-4.0) for more information.
252+
253+
Therefore, embedding Web Chat using the Direct Line secret directly is strongly discouraged because it would expose your secret on the client-side. Instead, the recommended approach is to exchange the secret for a Direct Line token on the server-side. This sample shows how to obtain and use the token.
254+
255+
### Avoiding user impersonation
256+
257+
Web Chat allows you to specify a user ID on the client-side, which will be sent in activities to the bot. However, this is susceptible to user impersonation because a malicious user could modify their user ID. Since the user ID typically isn't verified, this is a security risk if the bot stores sensitive data keyed on the user ID. For example, the built-in [user authentication support in Azure Bot Service](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-authentication?view=azure-bot-service-4.0) associates access tokens with user IDs.
258+
259+
To avoid impersonation, the recommended approach is for the server to bind a user ID to the Direct Line token. Then any conversation using that token will send the bound user ID to the bot. However, if the client is going to provide the user ID to the server, it is important for the server to validate the ID somehow (see below). Otherwise, a malicious user could still modify the user ID being sent by the client.
260+
261+
To keep things simple, this sample generates a random user ID on the server-side and binds it to the Direct Line token. While this mitigates impersonation concerns, the downside is that users will have a different ID every time they talk to the bot.
262+
263+
## Content of the local environment files
264+
265+
The `.env` / `appsettings.json` files hold the environment variable critical to run the service. These are usually security-sensitive information and must not be committed to version control. Although we recommend to keep them in [Azure Key Vault](https://azure.microsoft.com/en-us/services/key-vault/), for simplicity of this sample, we would keep them in local environment files.
266+
267+
To ease the setup of this sample, here is the template of the local environment files for each language.
268+
269+
<details><summary>JavaScript</summary>
270+
271+
### `/bot/.env`
272+
273+
```
274+
MICROSOFT_APP_ID=12345678-1234-5678-abcd-12345678abcd
275+
MICROSOFT_APP_PASSWORD=a1b2c3d4e5f6
276+
```
277+
278+
### `/web/.env`
279+
280+
```
281+
DIRECT_LINE_SECRET=a1b2c3.d4e5f6g7h8i9j0
282+
```
283+
284+
</details>
285+
286+
<details><summary>C#</summary>
287+
288+
### `/bot/appsettings.json`
289+
290+
```json
291+
{
292+
"Logging": {
293+
"LogLevel": {
294+
"Default": "Information",
295+
"Microsoft": "Warning",
296+
"Microsoft.Hosting.Lifetime": "Information"
297+
}
298+
},
299+
"AllowedHosts": "*",
300+
"MicrosoftAppId": "12345678-1234-5678-abcd-12345678abcd",
301+
"MicrosoftAppPassword": "a1b2c3d4e5f6"
302+
}
303+
```
304+
305+
### `/web/appsettings.json`
306+
307+
```json
308+
{
309+
"Logging": {
310+
"LogLevel": {
311+
"Default": "Information",
312+
"Microsoft": "Warning",
313+
"Microsoft.Hosting.Lifetime": "Information"
314+
}
315+
},
316+
"AllowedHosts": "*",
317+
"DirectLineSecret": "a1b2c3.d4e5f6g7h8i9j0"
318+
}
319+
```
320+
321+
</details>
322+
323+
# Frequently asked questions
324+
325+
## What if I need a consistent user ID across sessions/devices?
326+
327+
Instead of randomly generating user IDs, the backend API could leverage a user's existing identity from a true identity provider. The user would first sign in to the site before talking to the bot. That way, if the user signed in using the same identity on a different browser or device, the user ID would be the same. This would also prevent user impersonation because we could verify the user's identity with the identity provider before issuing a Direct Line token.
328+
329+
The flow could be:
330+
331+
1. The user signs in to the web app.
332+
1. The web app calls the backend API for generating Direct Line tokens, providing a verifiable user token.
333+
1. The backend API verifies the user token with the identity provider.
334+
1. The backend API uses the token to get an ID for the user. (The specifics will vary based on the identity provider and type of token.)
335+
1. The backend API generates a Direct Line token bound to the user ID (just as this sample does) and returns it to the web app.
336+
337+
# Further reading
338+
339+
- [Setting up a new Bot Channel Registration](https://docs.microsoft.com/en-us/azure/bot-service/bot-service-quickstart-registration?view=azure-bot-service-3.0)
340+
- [Generating a Direct Line token](https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication?view=azure-bot-service-4.0#generate-token)
341+
- [Enhanced Direct Line Authentication feature](https://blog.botframework.com/2018/09/25/enhanced-direct-line-authentication-features/)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[Bb]in/
2+
[Oo]bj/
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using Microsoft.Bot.Builder.Integration.AspNet.Core;
2+
using Microsoft.Bot.Builder.TraceExtensions;
3+
using Microsoft.Extensions.Configuration;
4+
using Microsoft.Extensions.Logging;
5+
6+
namespace TokenSampleBot
7+
{
8+
public class AdapterWithErrorHandler : BotFrameworkHttpAdapter
9+
{
10+
public AdapterWithErrorHandler(IConfiguration configuration, ILogger<BotFrameworkHttpAdapter> logger)
11+
: base(configuration, logger)
12+
{
13+
OnTurnError = async (turnContext, exception) =>
14+
{
15+
logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}");
16+
17+
await turnContext.SendActivityAsync("The bot encountered an error or bug.");
18+
await turnContext.SendActivityAsync("To continue to run this bot, please fix the bot source code.");
19+
20+
await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError");
21+
};
22+
}
23+
}
24+
}

0 commit comments

Comments
 (0)