[BotFramework]:有没有办法在C#中使用SDK V4开发的BOT中显示英雄卡或自适应卡中的Oauth提示?
[英] [BotFramework]: Is there a way to Display Oauth prompt in hero card or Adaptive card in a BOT Developed using SDK V4 in C#?
<脚本>(异步函数(){//在这个演示中,我们使用来自 MockBot 的 Direct Line 令牌.//要与您的机器人交谈,您应该使用使用 Direct Line 机密交换的令牌.//永远不要将 Direct Line 密码放在浏览器或客户端应用程序中.//https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authenticationconst res = await fetch('https://testbotforoauthprompt.azurewebsites.net//directline//token', { method: 'POST' });const { token } = await res.json();window.WebChat.renderWebChat({directLine: window.WebChat.createDirectLine({ token }),//我们正在添加一个新的中间件来处理卡片操作cardActionMiddleware: () =>下一个 =>异步 ({ cardAction, getSignInUrl }) =>{const { type, value } = cardAction;开关(类型){案例登录"://对于 OAuth 或登录弹出窗口,我们将直接打开 auth 对话框.const popup = window.open();const url = 等待 getSignInUrl();popup.location.href = url;休息;案例'openUrl':if (confirm(`你要打开这个网址吗?
${ value }`)) {window.open(value, '_blank');}休息;默认:return next({ cardAction, getSignInUrl });}}}, document.getElementById('webchat'));document.querySelector('#webchat > *').focus();})().catch(err => console.error(err));
</html>
进入您提供的链接无法打开它给我 404 错误
<
小时>
日期:2019 年 5 月 29 日原因:对 Richardson 提供的输入的进一步查询
我知道在生成令牌的控制器类中编写了一个 .NET 代码.有一个 html 页面可以加载我们的网络聊天,其中包含所需的脚本存储或公开令牌,然后每当我们打开此 HTML 文件时聊天机器人就会打开.但是,我有以下疑问.这些可能看起来很基本,但请耐心等待,因为我是编码新手:
代码应该写在哪里,如何调用,因为我没有在我的 html 脚本中指定或在任何地方调用 Controller 类 Index 方法来生成令牌并使用它?或者它会自动调用控制器内部的索引方法.如果没有,我应该在哪里自动指定你调用索引方法的这个?是否可以提供完整的解决方案,例如在解决方案中包含机器人代码和控制器类,以便我可以获得更好的图片,以便我可以询问任何其他进一步的查询(如果有)?
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:
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:
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";
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 *
});
}
Finally this prompt is added in the Dialogset or stack as below:
<!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?
${ 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:
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?
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?
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?
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:
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?
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:
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.
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.
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.
That's mostly right. See above responses.
Yes. Remove the POST method. Your code was very close!!