本文介绍了[BotFramework]:在使用C#SDK V4开发的BOT中,是否可以在英雄卡或自适应卡中显示Oauth提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#中的V4开发聊天机器人;我已经使用OauthCard提示在瀑布对话框中实现了身份验证功能,我希望此oauth卡提示显示在Hero卡或Adaptive卡或任何其他合适的登录卡中,以使登录功能可在Webchat Channel中使用.

当前,由于无法登录,因此在网络聊天频道中未显示oauth卡提示,因此请考虑是否可以在Hero卡或任何合适的卡中显示oauth Prompt的登录功能,然后继续进行操作身份验证功能.

我使用下面的链接启用了Oauth提示,它在模拟器中可以正常运行:

如何在不输入任何内容的情况下使用C#创建的SDK V4机器人的瀑布对话框中的oauth提示符下修复带有oauth提示的下一步导航?

但是无法在Webchat频道中执行此操作,因此认为如果将其保存在英雄卡中,它将可以正常工作.

由于我对BOT和编码还很陌生,请按详细的指导方式逐步提供代码或过程,以便我解决问题.

请帮助.

感谢&问候-ChaitayaNG

我不知道该怎么做,所以我尝试在index.html中执行以下操作: https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/18.customization-open-url

这对我也不起作用.

我也查看了以下链接,但根据我的理解,团队频道有评论,但网络聊天频道没有具体评论:

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

我也研究了以下链接,但是由于它与React相关,因此我没有进行调查,因为我正在网络聊天频道和Azure C#中使用聊天机器人:

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

我还尝试在Singin卡中调用oauth提示,该提示不起作用,因为它既不在模拟器中也不在Webchannel中调用提示.

因此,我需要帮助,因为即使遵循上述链接信息,oauth卡也不会在Web聊天频道中加载.因此,以为如果我们可以保留一些卡片,那是可以做到的,但是没有发现任何具体的事情也可以做.由于我是BOT和编码的新手,所以我可能错过了一些东西,因此请提供帮助或提供逐步操作指南.

预期结果:由于代码不起作用,所以需要在HeroCard或任何其他合适的卡内显示oauth提示,或者在Webchat通道中加载oauth提示可以在Emulator中正常工作.实际结果:不知道如何实现.

根据Richardson的评论添加详细信息:理查森,您好,

我在瀑布"对话框中使用了OauthPrompt,其中步骤1:我显示OAuthCard提示符,单击链接,它会弹出一个新窗口以输入凭据,并提供了一个神奇的代码.我在浏览器中输入魔术代码第2步:在这里,我正在获取令牌,并按照我说的那样在Emulator中正常工作,如下面的链接所述:

如何在不输入任何内容的情况下使用C#创建的SDK V4机器人的瀑布对话框中的oauth提示符下修复带有oauth提示的下一步导航?

来到Webchat时,向我显示了以下内容:[文件类型为'application/vnd.microsoft.card.oauth']

代替登录按钮或链接.

我使用的代码如下:

 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);
}
 

在称为Mainrootdialog类的maindialog中: 1.我有一个变量LoginPromptName = "loginprompt"和另一个用于连接名称的参数; public const string ConnectionName = "conname";

  1. 然后,我有一个名为提示符的方法,该方法接受连接名称并具有与oauthprompt相关的代码,如下所示:
   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. 最后,此提示如下所示添加到对话框集或堆栈中:
      public MainRootDialog(UserState userState)
            : base("root")
        {
            _userStateAccessor = userState.CreateProperty<JObject>("result");

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

如前所述,在上面的共享链接中,从我的评论中可以看到

但是在网络聊天频道中不会加载按钮或链接,这给了我: [文件类型为'application/vnd.microsoft.card.oauth']

我尝试了以下GitHub链接,但我无法粘贴或附加HTML文件以供参考: 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> 

进入您提供的链接后,它没有打开,则显示404错误


日期:2019年5月29日原因:有关Richardson提供的输入的进一步查询

我了解在生成令牌的控制器类中编写了一个.NET代码.有一个HTML页面可加载我们的网络聊天,其中包含必需的脚本来存储或公开令牌,然后只要打开此HTML文件,聊天机器人就会打开.但是,我有以下查询.这些看起来很基础,但是请耐心等待,因为我是编码的新手.

  1. 应该在哪里编写代码,如何调用该代码,因为我未在html脚本中指定还是在任何地方调用Controller类的Index方法来生成令牌并使用它?或者它将自动调用控制器内部的index方法.如果没有,我应该在哪里自动指定u调用索引方法?是否可以提供完整的解决方案,例如在解决方案中包含机器人代码和控制器类,以便获得更好的画面,以便我可以询问其他任何进一步的查询(如果有)?

  2. 此.net代码是单独的解决方案还是应该在同一机器人解决方案控制器类中编写?如果是单独的解决方案,那么如何将其以蓝色发布到BOT资源?僵尸程序和新解决方案如何在不提供任何连接的情况下自动交互?

  3. 我假设它应该在Visual Studio的同一BOT代码解决方案内创建一个新类.现在,我对此有进一步的查询(基于此假设):

a.根据我对您的解释的理解,post方法不起作用,因为没有令牌生成器,因此它给您一个错误.您可以使用下面的链接编写代码并获取令牌,该令牌再次带到第1个问题?

b.在HTML文件中,如果我按照上面的链接编写了给定的脚本,那么该脚本应位于相同的异步函数中,否则我们必须删除异步函数?

c.如果保持原样,像BOT Avatar之类的样式选项仍然起作用吗?其他脚本显示欢迎消息的方式是否相同?

d.在GetElementByID('')中,我们通过上面的链接传递了bot作为值,但在实际示例中,我们传递了网络聊天,是因为我们已经将POST方法更改为新脚本了吗?

e.应该保留张贴方法还是可以将其删除?代替发布行:

const res =等待获取(' https://examplebot.azurewebsites.net/directline/token ',{方法:'POST'}); 编写如下所示的新脚本:下面给出的脚本(摘自上面的链接):

@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. 您还解释了为避免所有这些复杂性并使它变得简单,只需将您的秘密保存在文件中即可:当前:const {token} =等待res.json();简单起见:const {token} =<>;是我的理解对吗?

  2. 在第四个问题之上:然后,也应删除POST方法行,即行下方,而我们不必编写新的控制器类或Model config上面给出的脚本,其余保持原样:如下所示,当我打开页面并且OAuth提示和自适应卡可以正常工作时,自动程序会加载:

    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>
    

我的理解对吗?


2019年5月30日ChaitanyaNG的评论更新:屏幕截图:供您参考使用Richardson提供的HTML文件并将其替换为我的BOT Direct Channel密钥

的发现.

解决方案

真正的问题在您的评论中:

这是由以下原因引起的:

 <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();
 

第一个问题:您同时使用iframe(<iframe src='https://webchat...) WebChat(<script> (async function ()...).

修复:删除iframe,仅使用WebChat代码.这在任何地方都没有真正记载,但是iFrame使用的是botchat,这是WebChat的较旧版本,它不能与OAuth配合使用,并且会给您带来[File of type...错误.

第二个问题:您没有获得有效的令牌

该代码返回404,因为https://testbotforoauthprompt.azurewebsites.net/directline/token不存在.

您应该按照代码注释中链接的指南进行操作,这样您可以向标头中的Authorization: Bearer <YourSecretFromAzurePortal>发出https://directline.botframework.com/v3/directline/tokens/generate的POST请求.

或者,您可以直接使用const token = <YourSecretFromAzurePortal>.请注意,直接使用您的秘密不是一个好主意.您应该真正设置一个令牌服务器. 这应该会让您入门(注意:这是链接我打算在上面的评论中使用),但是稍微复杂一点.如果您只想要简单的东西,而又不在乎您的应用程序密码是否泄露,请使用const token = <YourSecretFromAzurePortal>方法.

我刚刚在这里回答了类似的问题.


关于您的更新

令牌生成器

关于:此答案

如果您想将Secret保密,则需要编写自己的令牌服务器.链接答案的前半部分说明了执行此操作的基本方法.您既可以编写自己的代码,也可以在该链接的答案中使用示例,也可以使用在该答案中链接的博客文章中的代码.

将代码放置在何处取决于您希望其运行的方式. 样本令牌服务器完全是与漫游器分开. 博客帖子示例显示如何将其集成到您的bot中(尽管您也可以单独托管它).

WebChat客户端向该令牌服务器发出请求,该令牌服务器向https://directline.botframework.com/v3/directline/tokens/generate发出请求并返回响应,该响应是有效的DirectLine令牌.

但是,在许多情况下,您不需要编写自己的令牌服务器的额外安全性.链接答案的后半部分说明,对于许多简单的漫游器而言,暴露秘密的安全风险很小.

我建议您(因为您说过对编码非常陌生),所以不要编写自己的令牌服务器,而只将机密公开在const token = <Directline secret from azure portal direct line channel>;中(请注意,我删除了{} ,因为您的令牌是string).如果您真的想使用令牌服务器,则需要学习如何用C#编写服务器.

HTML文件

examplebot.azurewebsites...获得的代码使用Angular(我认为).老了不要使用它.

您应基于 WebChat示例之一创建HTML代码. .

看起来就像您的最后一个代码块一样.既然存在很多困惑,请使用以下方法:

 <!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>
 

回答您的问题

a.正确的. POST方法不起作用,因为您使用的链接上没有令牌服务器.

b.使用上面的代码

c.是的,您可以根据需要设置样式.由于'DIRECT_LINE/CONNECT_FULFILLED'代码,欢迎消息应该起作用.您可以从WebChat示例中添加其他代码来完成其他事情,是的.

d.不要使用在getElementById中传递"bot"的代码.使用WebChat示例中的代码或我发布的代码

e.除非使用令牌服务器,否则删除post方法.

  1. 那基本上是对的.请参阅以上回复.

  2. 是的.删除POST方法.您的代码非常接近!


确保您使用的令牌来自此处:

I 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

解决方案

The real issue is in your comment here:

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

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:

这篇关于[BotFramework]:在使用C#SDK V4开发的BOT中,是否可以在英雄卡或自适应卡中显示Oauth提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 14:35