0
votes

enter image description hereI am developing a chatbot using V4 in C#; I have implemented an authentication functionality inside a waterfall dialog using OauthCard prompt, I want this oauth card prompt to be displayed inside a Hero Card or Adaptive card or any other card that is suitable such that Login functionality works in Webchat Channel.

Currently, the oauth card prompt is not displayed in the webchat Channel as a result I am unable to login so thought if I can display the sign in functionality of oauth Prompt in Hero card or any suitable card then I can proceed it with authentication functionality.

I have enabled Oauth Prompt using the below link and it perfectly works fine in emulator:

How to fix next step navigation with oauth prompt in waterfall dialog in SDK V4 bot created using C# without typing anything?

But not able to do it in Webchat Channel hence thought if i keep this in hero card it can work.

  • Language: C#
  • SDK: V4
  • Channel: WebChat channel

Please provide the code or procedure in step by step in a detailed guide manner as I am fairly new to BOT and coding so that i can fix my issue.

Please help.

Thanks & Regards -ChaitayaNG

I do not know how to do it so i tried do the following in index.html: https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/18.customization-open-url

This is did not work for me either.

I looked into the below links also but according to my understanding there was comments for Team Channel but nothing concrete for webchat channel:

https://github.com/microsoft/botframework-sdk/issues/4768

I also looked into belowlink but since it was related to React i did not investigate it as i am doing the chatbot in webchat channel and in azure C#:

https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/10.a.customization-card-components

I also tried to call oauth prompt inside Singin card which did not work as it was not invoking the prompt either in Emulator or Webchannel.

Hence i need help as the oauth cards are not loading in Web Chat channel even after following above links information. So thought if we can keep in some cards it can be done but did not find any thing concrete to do also. Since i am new to BOT and coding i may have missed something so please help or provide step by step guide on how t do it.

Expected Result: Need the oauth prompt to be displayed inside a HeroCard or any other suitable card as it is code is not working or loading the oauth prompt in Webchat channel working fine in Emulator. Actual Result: Do not know how to achieve it.

Adding details as per the comments from Richardson: Hi Richardson,

I have used OauthPrompt in a Water fall dialog where in STEP 1: I display OAuthCard prompt where i click on link and it pops up a new window to enter credentials and it gives a magic code. I enter the magic code in browser it goes to STEP 2: Here i am retrieving token and proceeding further as i said this is working in Emulator as described in below link:

How to fix next step navigation with oauth prompt in waterfall dialog in SDK V4 bot created using C# without typing anything?

Coming to Webchat it displayed me the following: [File of type 'application/vnd.microsoft.card.oauth']

Instead of sign in button or link.

The code i used is the following:

public class LoginDialog : WaterfallDialog
{
    public LoginDialog(string dialogId, IEnumerable<WaterfallStep> steps = null)
         : base(dialogId, steps)
    {
        AddStep(async (stepContext, cancellationToken) =>
        {
            await stepContext.Context.SendActivityAsync("Please login using below option in order to continue with other options...");

            return await stepContext.BeginDialogAsync("loginprompt", cancellationToken: cancellationToken); // This actually calls the  dialogue of OAuthPrompt whose name is  in EchoWithCounterBot.LoginPromptName.  


        });

        AddStep(async (stepContext, cancellationToken) =>
        {
            Tokenresponse = (TokenResponse)stepContext.Result;

            if (Tokenresponse != null)
            {

                await stepContext.Context.SendActivityAsync($"logged in successfully... ");


                return await stepContext.BeginDialogAsync(DisplayOptionsDialog.Id); //Here it goes To another dialogue class where options are displayed
            }
            else
            {
                await stepContext.Context.SendActivityAsync("Login was not successful, Please try again...", cancellationToken: cancellationToken);


                await stepContext.BeginDialogAsync("loginprompt", cancellationToken: cancellationToken);
            }

            return await stepContext.EndDialogAsync();
        });
    }

    public static new string Id => "LoginDialog";

    public static LoginDialog Instance { get; } = new LoginDialog(Id);
}

In the maindialog called as Mainrootdialog class: 1. I have a variable LoginPromptName = "loginprompt" and another parameter for connection name; public const string ConnectionName = "conname";

  1. Then I have a method called prompt which accepts connection name and has oauthprompt related code as given below:
  private static OAuthPrompt Prompt(string connectionName)
        {
            return new OAuthPrompt(
               "loginprompt",
               new OAuthPromptSettings
               {
                   ConnectionName = connectionName,
                   Text = "signin",
                   Title = "signin",
                   Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 
               });
        }
  1. Finally this prompt is added in the Dialogset or stack as below:
     public MainRootDialog(UserState userState)
            : base("root")
        {
            _userStateAccessor = userState.CreateProperty<JObject>("result");

            AddDialog(Prompt(ConnectionName));
            AddDialog(LoginDialog.Instance);            
            InitialDialogId = LoginDialog.Id;
        }

As tried to explain earlier works perfectly fine in emulator as you could see from my comments in the above shared link

But in webchat channel does not load button or link gives me this: [File of type 'application/vnd.microsoft.card.oauth']

I tried the following GitHub link which i did not work pasting or attaching the HTML file for reference: https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/18.customization-open-url

<!DOCTYPE html>
<html lang="en-US">
<head>
    <title>Web Chat: Customize open URL behavior</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!--
      For demonstration purposes, we are using the development branch of Web Chat at "/master/webchat.js".
      When you are using Web Chat for production, you should use the latest stable release at "/latest/webchat.js",
      or lock down on a specific version with the following format: "/4.1.0/webchat.js".
    -->
    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
    <style>
        html, body {
            height: 100%
        }

        body {
            margin: 0
        }

        #webchat,
        #webchat > * {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
<body>
    <div id="webchat" role="main">
        <iframe src='https://webchat.botframework.com/embed/TestBotForOauthPrompt?s=<<Given my secretkey of web chat channel>>' style='min-width: 400px; width: 100%; min-height: 500px;'></iframe>
    </div>
    <script>
      (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
        const res = await fetch('https://testbotforoauthprompt.azurewebsites.net//directline//token', { method: 'POST' });
        const { token } = await res.json();
        window.WebChat.renderWebChat({
          directLine: window.WebChat.createDirectLine({ token }),
          // We are adding a new middleware to handle card action
          cardActionMiddleware: () => next => async ({ cardAction, getSignInUrl }) => {
            const { type, value } = cardAction;
            switch (type) {
              case 'signin':
                // For OAuth or sign-in popups, we will open the auth dialog directly.
                const popup = window.open();
                const url = await getSignInUrl();
                popup.location.href = url;
                break;
              case 'openUrl':
                if (confirm(`Do you want to open this URL?\n\n${ value }`)) {
                  window.open(value, '_blank');
                }
                break;
              default:
                return next({ cardAction, getSignInUrl });
            }
          }
        }, document.getElementById('webchat'));
        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>
</body>
</html>

Coming to the link you have provided it does not open it gives me 404 error


Date: 29-May-2019 Reason: Further queries on inputs provided by Richardson

I understand there is a .NET Code written inside a controller class which generates the Token. There is a html page to load our web chat which contains required scripts to store or expose tokens and then the chat bot opens whenever we open this HTML file. However, I have following queries. These might seem very basic but please bear with me as I am new to coding:

  1. Where the code should be written, how will it get called because I am not specifying in my html script or anywhere call the Controller class Index method to generate the token and use it? Or will it call automatically the index method inside controller. If not, automatically where should I specify this that u call index method? Is it possible to provide whole solution like having bot code and controller class at solution so that I can get a better picture so that I can ask any other further queries if any?

  2. Is this .net code is a separate solution or inside the same bot solution controller class should be written? If separate solution, then how to publish this to the BOT resource in azure? How bot and new solution will interact automatically without providing any connection?

  3. I am assuming it should a new class inside the same BOT Code solution in Visual Studio. Now, I have further queries on this(based on this assumption):

a. As per my understanding on your explanation the post method is not working because there is no Token generator, so it gives you an error. You can use the below link to write the code and get the token which again brings to question number 1?

What is the correct way to authenticate from JavaScript in an HTML file to the Microsoft Web Chat control for Bot Framework v4?

b. In the HTML file if I write the script given as per above link then should be in the same async function or we have to remove the async function?

c. Still the style options like BOT Avatar and etc work if kept as is ? same way other scripts for displaying welcome message?

d. In the GetElementByID('') we are passing bot as the value from the link above but in actual samples we pass web chat is it because we have changed the POST method to the new script?

e. Should the post method still be kept or can be removed? Instead of the post line:

const res = await fetch('https://examplebot.azurewebsites.net/directline/token', { method: 'POST' }); Write new one as below: the script given below (taken from above link):

@model ChatConfig
@{
    ViewData["Title"] = "Home Page";
}
<link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />
<div id="bot" />
<script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>
<script>
      BotChat.App({
          directLine: {
              secret: '@Model.Token'
          },
        user: { id: @Model.UserId },
        bot: { id: 'botid' },
        resize: 'detect'
      }, document.getElementById("bot"));
</script>
  1. You have also explained that to avoid all these complications and make it simple just keep your secret in the file: Current: const { token } = await res.json(); To make it simple: const { token } = <>; Is my understanding, right?

  2. On top of 4th question: Then the POST method line should also be removed i.e. below line and we don’t have to write the new controller class or the script given above of Model config and rest keep as is: Something like below and the bot loads when I open the page and the OAuth prompts and adaptive cards work without any issue:

    Avanade D365 F&O Assets BOT

    <!--
      For demonstration purposes, we are using development branch of Web Chat at "/master/webchat.js".
      When you are using Web Chat for production, you should use the latest stable at "/latest/webchat.js".
      Or locked down on a specific version "/4.1.0/webchat.js".
    -->
    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
    <style>
        html, body {
            height: 100%
        }
    
        body {
            margin: 0
        }
    
        #webchat {
            height: 100%;
            width: 100%;
        }
    </style>
    

    </div>
    <script>
      (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
    
          const { token } = <<Directline secret from azure portal durect line channel>>;
    
          const styleOptions = {
           botAvatarImage: 'https://docs.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
           botAvatarInitials: 'BF',
           userAvatarImage: 'https://avatars1.githubusercontent.com/u/45868722?s=96&v=4',
           userAvatarInitials: 'WC',
           bubbleBackground: 'rgba(0, 0, 255, .1)',
           bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
      };
        // We are using a customized store to add hooks to connect event
        const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
          if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
            // When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
            dispatch({
              type: 'WEB_CHAT/SEND_EVENT',
              payload: {
                name: 'webchat/join',
                value: { language: window.navigator.language }
              }
            });
          }
          return next(action);
        });
        window.WebChat.renderWebChat({
          directLine: window.WebChat.createDirectLine({ token }),
          store
        }, document.getElementById('webchat'));
        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>
    

Is my understanding, right?


30 May 2019 ChaitanyaNG Updates for the Comment: Screenshot: For reference on the findings of using the HTML file provided by Richardson as is and replacing it by my BOT Direct Channel secret key

1
You should use OAuthPrompt. It does much more than just open a link, which is about all you can expect a Hero Card to do. OAuthPrompt should work in WebChat if it works in Emulator--Emulator runs on WebChat. What, specifically, isn't working about it? Can you share your code? This GitHub issue might help you get OAuth working in WebChat.mdrichardson
Hi Richardson, Due to characters limitations i have added my comments back in original post where i have given my code and what all things i have tried as much as i can. Coming to the link off GitHub issue it does not open for me it gives 404 error page. Please help in solving this issue and also please let me know if any other details are needed or please point out me in detailed step by step manner if i had done anything incorrect.Chaitanya N G
Although your edit was rejected (not by me), I read it. It looks like you still use the iframe in your code.mdrichardson
Hi again, Thanks for your inputs. Please find my further queries added back to my original query due to space limitations in comments. Can you please provide your inputs or correct my understanding wherever required so that i can proceed further?Chaitanya N G
recently I am started getting UI issue, Chat window is not visible perfectly, it was visible 4 days ago but some issue recently. I didn't make any changes in bot service etc. is this service issue? or something else? Note: I have embed URL into sharepoint page. Can someone help me?Anil Patel

1 Answers

1
votes

The real issue is in your comment here:

Coming to Webchat it displayed me the following: [File of type 'application/vnd.microsoft.card.oauth']

which is caused by:

<div id="webchat" role="main">
        <iframe src='https://webchat.botframework.com/embed/TestBotForOauthPrompt?s=<<Given my secretkey of web chat channel>>' style='min-width: 400px; width: 100%; min-height: 500px;'></iframe>
    </div>
    <script>
      (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
        const res = await fetch('https://testbotforoauthprompt.azurewebsites.net//directline//token', { method: 'POST' });
        const { token } = await res.json();

First issue: You're using both the iframe (<iframe src='https://webchat...) and WebChat (<script> (async function ()...).

Fix: Remove the iframe and just use the WebChat code. This isn't really documented anywhere, but the iFrame uses botchat, which is an older version of WebChat, which doesn't work with OAuth and is what's giving you the [File of type... error.

Second issue: You aren't getting a valid token

const res = await fetch('https://testbotforoauthprompt.azurewebsites.net//directline//token', { method: 'POST' });

That code returns a 404 because https://testbotforoauthprompt.azurewebsites.net/directline/token doesn't exist.

You should follow the guide linked in the code comments, which would have you make a POST request to https://directline.botframework.com/v3/directline/tokens/generate with Authorization: Bearer <YourSecretFromAzurePortal> in the header.

Alternatively, you can use const token = <YourSecretFromAzurePortal> directly, instead. Note that it isn't a good idea to use your secret directly. You should really set up a token server. This should get you started (note: this is the link I intended to use in my comment above), but it's a little more complex. If you just want something simple and don't care if your app secret gets out, go with the const token = <YourSecretFromAzurePortal> method.

I just answered a similar question, here.


Regarding your updates

Token Generator

Regarding: this answer

If you want to keep your Secret private, you need to write your own token server. The first half of the linked answer explains a basic way to do this. You can either write your own, use the sample in that linked answer, or use the code from the blog posts that are linked in that answer.

Where to put the code is dependent on how you want it to run. The sample token server is entirely separate from the bot. The blog post samples show how to integrate it into your bot (although you can also host it separately).

The WebChat client makes a request to that token server, which makes a request to https://directline.botframework.com/v3/directline/tokens/generate and returns the response, which is a valid DirectLine token.

However, in many cases you don't need the extra security of writing your own token server. The second half of the linked answer explains that the security risks of exposing your secret are minimal for many simple bots.

I recommend, for you (since you said you're fairly new to coding), that you don't write your own token server and just leave the secret exposed in const token = <Directline secret from azure portal direct line channel>; (Note that I removed the {}, since your token is a string). If you really want to use a token server, you'll need to learn how to write a server in C#.

HTML File

The code you got from examplebot.azurewebsites... uses Angular (I think). It's old. Don't use it.

You should base your HTML code off of one of the WebChat Samples.

It looks like your last code block does. Since there's been a lot of confusion, just use this:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>Web Chat: Custom style options</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--
      For demonstration purposes, we are using the development branch of Web Chat at "/master/webchat.js".
      When you are using Web Chat for production, you should use the latest stable release at "/latest/webchat.js",
      or lock down on a specific version with the following format: "/4.1.0/webchat.js".
    -->
    <script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
    <style>
        html, body {
            height: 100%
        }

        body {
            margin: 0
        }

        #webchat {
            height: 100%;
            width: 100%;
        }
    </style>
  </head>
  <body>
    <div id="webchat" role="main"></div>
    <script>
      (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication

        // Token is found by going to Azure Portal > Your Web App Bot > Channels > Web Chat - Edit > Secret Keys - Show
        // It looks something like this: pD*********xI.8ZbgTHof3GL_nM5***********aggt5qLOBrigZ8
        const token = '<Directline secret from azure portal durect line channel>';

        // You can modify the style set by providing a limited set of style options
        const styleOptions = {
            botAvatarImage: 'https://docs.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
            botAvatarInitials: 'BF',
            userAvatarImage: 'https://avatars1.githubusercontent.com/u/45868722?s=96&v=4',
            userAvatarInitials: 'WC',
            bubbleBackground: 'rgba(0, 0, 255, .1)',
            bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
        };

        // We are using a customized store to add hooks to connect event
        const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
        if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
            // When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
            dispatch({
            type: 'WEB_CHAT/SEND_EVENT',
            payload: {
                name: 'webchat/join',
                value: { language: window.navigator.language }
            }
            });
        }
        return next(action);
        });

        window.WebChat.renderWebChat({
          directLine: window.WebChat.createDirectLine({ token }),
          styleOptions
        }, document.getElementById('webchat'));

        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>
  </body>
</html>

Answering your questions

a. Correct. POST method is not working because there wasn't a token server at the link you were using.

b. Use the code I have above

c. Yes, you can style however you want. Welcome messages should work because of the 'DIRECT_LINE/CONNECT_FULFILLED' code. You can add additional code from the WebChat samples to accomplish other things, yes.

d. Don't use the code that passes "bot" in getElementById. Use the code from the WebChat samples or the code I posted

e. Remove the post method unless you're using a token server.

  1. That's mostly right. See above responses.

  2. Yes. Remove the POST method. Your code was very close!!


Ensure the token you use comes from here:

enter image description here