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:
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#:
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:
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:
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:
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>
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
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