Ahosti.Com
Read trending IT updates for cloud businesses, managed service providers, IT pros & what innovation digital transformation is driving in tech industry.

Embed a bot in an internet web page utilizing Internet Chat

0 10

This publish describes the way to embed a bot in an internet web page utilizing the Bot Framework Internet Chat. The Internet Chat management is a highly-customizable web-based consumer for the Bot Framework V4 SDK. It makes use of the  Direct Line channel, related to the bot, to permit the person to speak with the bot from throughout the net web page.

In its essence, this publish reveals the way to generate a Direct Line token with out exposing the Direct Line secret. It does so by separating the server code, which generates the token, from the consumer code (net web page) which makes use of the token to render the Internet Chat, with out exposing any secret. Though the Server is operating domestically on http://localhost:3000, it’s a simulated model of what you’ll do in an precise manufacturing surroundings.

Any bot registered with the Bot Framework is mechanically configured for the Internet Chat channel which incorporates the Internet Chat management to permit communication with the bot. As described within the Join a bot to Internet Chat article, a standard option to embed a bot in a web site is utilizing an iframe HTML aspect. The issue with the strategy described within the article is that it exposes the Internet Channel secret within the consumer net web page. This may be acceptable throughout growth however not in manufacturing.

WARNING! In manufacturing, it’s strongly advocate that you simply use a token as an alternative of your secret. See Secrets and techniques and tokens .

Obtain the instance code right here.

Giving credit score. The instance code proven on this publish has been tailored from Consumer-specific Direct Line token pattern. There you’ll find a extra full implementation that features the JavaScript model. Many because of Nafis Zaman.

Stipulations

Instance Elements

The next determine reveals the parts concerned within the instance used on this publish.

  1. Server. Also called the API, it performs the Direct Line token acquisition. It verifies the person’s identification and acquires a Direct Line token certain to that identification.
  2. Consumer. A static index.html web page that may be hosted utilizing any net server. It requires the person to check in. Then it makes a request to the server with proof of the person’s identification. It obtains the Direct Line token from the sever and makes use of it to render the Internet Chat.
  3. Bot The instance assumes that you have already got a bot requiring person’s authentication and deployed in Azure. See Tutorial: Create and deploy a fundamental bot

Safety Concerns

Internet Chat secret

When embedding a Internet Chat in an internet web page, you possibly can present both a Direct Line secret or a Direct Line token so the Internet Chat can talk with the bot.

  • The Direct Line secret can be utilized to entry the entire bot’s conversations; it doesn’t expire.
  • The Direct Line token can solely be used to entry a single dialog; it does expire. For extra data, see the Direct Line Authentication article.

WARNING! The usage of the Direct Line secret in an net web page is strongly discouraged. The really helpful strategy is to trade the key for a token with the assistance of a Direct Line token generator server.

Consumer impersonation

The Internet Chat permits to specify a person ID, which is distributed to the bot. Sometimes, the person ID is just not verified and this may occasionally permit person impersonation by hackers.

WARNING! Unverified person IDs are a safety threat if the bot shops delicate knowledge primarily based on person ID. For instance, the built-in person authentication help in Azure Bot Service associates entry tokens with person IDs.

To keep away from impersonation, the really helpful strategy is for the server to bind a person ID to the Direct Line token. Then any dialog utilizing that token will ship the certain person ID to the bot. Nonetheless, if the consumer offers the person ID to the server, it is crucial for the server to validate the ID.

The popular strategy is to leverage a person’s current identification from an identification supplier. The person should first check in to the location earlier than speaking to the bot. This prevents person impersonation as a result of the person’s identification is verified by the identification supplier.

Server Highlights

The simulation server runs on localhost port 3000 (localhost:3000) . It makes use of the saved Direct Line secret to acquire the Direct Line token, see the associated instructions within the Operating the Instance, Server part.  The next are the highlights of the server facet logic:

  1. Within the physique of the POST request, the Internet Chat ship to the server an OpenID Join (OIDC) JWT, known as ID token, that identifies the person.
  2. The server validates the ID token in opposition to the chosen identification supplier (Azure Energetic Listing within the instance).
  3. It builds a person ID utilizing claims from the validated token. The instance makes use of the sub (topic) declare as a result of it’s a typical OIDC declare that uniquely identifies the person, and it doesn’t require any further scopes. Discover the next:
    1. Within the Azure Energetic Listing, the sub declare is just constant per person per software. This implies the person ID wouldn’t be ample for trying up the person in different methods (equivalent to Microsoft Graph). If we would have liked a person ID that identifies the person throughout functions, we may use the oid (object ID) declare, but it surely requires the profile scope. See AAD ID token claims for extra particulars
    2. Because the person identification is verified, it’s okay for this person ID to be a guessable worth.
  4. It retrieves a person ID certain Direct Line token utilizing the Direct Line API.
  5. It responds with the user-specific Direct Line token.

Consumer Highlights

Relying on the situation, the Server API might be known as from a consumer, equivalent to a single-page software, or a server, equivalent to a extra conventional net app, the place tokens are dealt with server-side. The one requirement is that the caller can present a person ID token from the anticipated identification supplier. If you’re embedding the bot in an authenticated web site, then you could have already got an ID token that you should utilize.

The simulation consumer run on localhost port 5500 (localhost:5500) . It makes use of the saved Direct Line secret to acquire the Direct Line token, see the associated instructions within the Operating the Instance, Consumer part.

Code highlights

Receiving the ID token

The Server API expects the person ID token to be handed within the request physique:

// DirectLineTokenController.cs

public class TokenRequest
{
    [JsonPropertyName("id_token")]
    public string idToken { get; set; }
}
...
public async Job Submit([FromBody] TokenRequest request)
{
    ...
}

Tokens are usually despatched as bearer tokens within the Authorization header. Nonetheless, the instance doesn’t use the person’s ID token to guard the API. Somewhat, it’s a parameter of the request itself. Though the API isn’t protected, you possibly can shield the API utilizing a distinct token (equivalent to an OAuth entry token) which would go within the Authorization header. See additionally What’s the OAuth 2.0 Bearer Token precisely?.

Validating the ID token

The instance makes use of two packages to realize token validation: Microsoft.IdentityModel.Protocols.OpenIdConnect and System.IdentityModel.Tokens.Jwt. The instance first retrieves the Azure AD public keys used to signal the token after which validate the token:

// DirectLineTokenController.cs
var configurationManager = new ConfigurationManager(
    "https://login.microsoftonline.com/widespread/v2.0/.well-known/openid-configuration",
    new OpenIdConnectConfigurationRetriever(),
    new HttpDocumentRetriever());
...
var discoveryDocument = await configurationManager.GetConfigurationAsync(ct);
var signingKeys = discoveryDocument.SigningKeys;

// DirectLineTokenController.cs
var principal = new JwtSecurityTokenHandler()
    .ValidateToken(token, validationParameters, out var rawValidatedToken);

Calling the API and rendering Internet Chat

After the person indicators in, the consumer calls the Server API with the person’s ID token and makes use of the ensuing Direct Line token to render the Internet Chat.

Observe that the web page does not specify a person ID when initiating the Internet Chat. Direct Line will deal with sending the person ID to the bot primarily based on the token.

// index.html
async operate getDirectLineToken(idToken) {
    const res = await fetch('http://localhost:3000/api/direct-line-token', {
        technique: 'POST',
        headers: {
            'Content material-Sort': 'software/json',
        },
        physique: JSON.stringify({ id_token: idToken }),
    });
    ...
    return await res.json();
}
...
const directLineTokenResponse = await getDirectLineToken(idToken);
...
WebChat.renderWebChat(
    {
        directLine: WebChat.createDirectLine({ token: directLineTokenResponse.token }),
    },
    doc.getElementById('webchat')
);

Run the instance

There are 2 sides concerned when operating the instance: server and consumer.

Obtain the instance code right here.

Server

To run the server software you’ll use the dotnet command particularly dotne user-secrets set  to retailer the Direct Line secret and dotnet run to run the server software from the supply code.

In a terminal window execute the next instructions:

  1. Change to the server listing, the place the server API software is: cd ..servercsharp.
  2. In your code editor, open the appsettings.json file. Assign the next worth: "TokenValidationSettings": {"ValidAudience": "" }.
  3. Retailer the Direct Line secret: dotnet user-secrets set "DirectLine:DirectLineSecret" "".
  4. Run the server API: dotnet run.
Variable Worth Description
"TokenValidationSettings": {"ValidAudience": "" }   The Azure AD identification supplier app ID. You assign this worth within the appsettings.json file.
  The Direct Line secret related to the bot.

Consumer

After receiving the Direct Line token, the caller can then use it to render the Internet Chat. The bot will obtain a constant person ID that it might depend upon.

In a terminal window execute the next instructions:

  1. Change to the consumer listing, the place the index.html web page is:  cd ..consumer.
  2. Open the index.html in your favourite editor, and assign  the next values to the empty variables :


    Variable Worth Description
    AAD_APP_ID The Azure AD identification supplier app ID. Used to authenticate the bot’s customers.
    AAD_REDIRECT_URI  http://localhost:5500 Bear in mind so as to add the redirect URI http://localhost:5500to your Azure AD identification supplier.
  3. To be able to “serve” the online web page on localhost:5500 you’ll use the npx http-server command to run an area net server.


    Run an area net server on the desired port:  npx http-server ./ -p 5500. 


  4. In your browser navigate to http://localhost:5500. It will show the static index.html web page and prompts the Internet Chat.
  5. You can begin chatting with the bot.

The next figures present an instance of a easy and a personalized Internet Chat:

You might also like
Loading...