Microsoft Bot Framework (Node.js- SDK4) + Microsoft Graph API - botframework

Is it possible that the Microsoft Bot Framework Node.js - SDK4 automatically identify a logged in user from a Microsoft account (like a user that is logged in Sharepoint) so that I can use Microsoft Graph services directly on the bot without needing to ask user login and password?
I'm asking that because I have a bot running on a sharepoint page, and in theory, the user already will be logged in on a microsoft account when he starts talking to the bot.

Check this code.
{ ResponseIds.Greeting, (context, data) => {
var greetings = JsonConvert.DeserializeObject<Greetings>
(MainStrings.GREETING);
Random r = new Random( );
int index = r.Next( greetings.messages.Count );
return greetings.messages[index].message.Replace("
{username}",context.Activity.From.Name);
}
Else I have seen an authentication dialog that probably does a similar operation

Related

How to send message activity from Web Chat Bot to Microsoft Teams channel

I have created a Echo Bot in c# using QnA maker which is working absolutely fine now I wanted to achieve a scenario where if user ask any question and bot unable to find related answer than this question must be sent on Microsoft Teams channel where except will reply to the same and that message will sent to the user.
So, Is there any way to send message user message to Microsoft Teams for expert reply. If you have any sample code for the scenario please feel free to mention.
As per your current requirement this is kind of handoff or human live agent connect.
The following way you can achieve posting a message in ms team ( Go through this article Send proactive messages to Teams channels and users ).
Send proactive messages to Teams channels and users ( Microsoft Bot Framework v4 )
The user should be part of ms teams ( Azure AD valid users ).
Suggestions : If you are using domain bot then human live agent or handoff concept is the best approach otherwise you can integrate bin search api or any other third party api for unanswered question.
As per your requirement you can use Graph API to send message to channel using below code
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var chatMessage = new ChatMessage
{
Body = new ItemBody
{
Content = "Hello World"
}
};
await graphClient.Teams["{team-id}"].Channels["{channel-id}"].Messages
.Request()
.AddAsync(chatMessage);
Please go through this documentation for more info.

Relationship between Teams Messaging Extension with action command, the underlying bot and access via Graph API

I want to call a messaging extension (with action command) and access Graph API via a bot for getting different resources of the channel (e.g. retrieve all messages or get replies for my message).
In the examples from Microsoft it is stated as a prerequisite that I have to do the "Bot channels registration" so that the access of the bot to the Graph API via OAuth2 works.
Do I really need this channel registration? Or is there another way?
As a test, I had created a azure free trial, with which I performed the "Bot channels registration" and could also save the ID and secret for the Graph Api access in the registration. With this I had success. Now the 30 days testing period is over and I'm interested in whether it would work without.
Thanks for your help
Update:
Thats my code to initialize graph api:
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(AppId)
.WithClientSecret(AppSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{Tenant}"))
.Build();
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
AuthenticationResult authenticationResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();
var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
return Task.FromResult(0);
}));
For OAuth authentication, you need to register the bot with azure for sure.

Access O365 Modern Groups information from VSTO Outlook Add-in

I want to build an add-in for the MS Outlook 2019 desktop app (-> VSTO add-in). It is intended to gather some information from O365 Modern Groups that the current Outlook user (me) is a member of. As far as I understand the only way to achieve this is to use Microsoft Graph API because there is no support to access O365 related things via Outlook object model/Office Interop. Given that (and please correct me if I am wrong) I might use the Microsoft.Graph Nuget packages. With them I would like to call the following endpoint:
POST /users/{id | userPrincipalName}/getMemberGroups
possible in C# with this code snippet:
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var securityEnabledOnly = true;
await graphClient.Me
.GetMemberGroups(securityEnabledOnly)
.Request()
.PostAsync();
My question is: Is there a way of using the existing Outlook credentials for the authProvider so that I don't need the user to enter credentials?
I read that web add-ins have the possibility to use different authentication flows including a SSO flow. But that does not fit for VSTO.
I thought of a IntegratedWindowsAuthenticationProvider. But therefore I need to provide a clientId which I do not have. Does that ultimately mean that I need to register my add-in in some way? Can't I just write an add-in for my personal purposes without admin support?
IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantID)
.Build();
IntegratedWindowsAuthenticationProvider authProvider = new IntegratedWindowsAuthenticationProvider(publicClientApplication, scopes);

How to pass the password activity form bot to the front end in microsoft bot framework

I am trying to implement the functionality of the password as shown in this link.
https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/05.custom-components/f.password-input
but how to pass the password activity form the bot to the front end. I am using the c# template for the developing the bot.
As per my understanding, we need to pass a password activity from the bot to the front-end for the execution of the password things as mentioned in the link.
An example would be help-full in knowing how to pass this type of customer activity forms the bot.
Thanks,
I used this sample myself for one of my bots. The bot logic is built in node but I guess it shouldn't be hard to translate to c#
const askPwd =
{
name: 'passwordInput',
type: 'event'
};
await stepContext.context.sendActivity(askPwd);
return await stepContext.prompt(PASSWORD_PROMPT, '');
In c# this will probabaly translate into something like this (I don't know c#):
Activity activity = new Activity
{
Type = ActivityTypes.Event,
Name = "passwordInput"
};
await stepContext.Context.SendActivityAsync(activity, cancellationToken);});

Securing traffic from Microsoft Teams to a bot?

How to secure the traffic from Microsoft Teams to a bot, so that bot could be answering on company specific questions / discussions and would not need to be exposed as anonymous WebAPI?
Bot integration to Teams UIs is easy from bot framework side, but right now there's no documentation for how to isolate bot only for specific enterprise.
Business case - We want to build enterprise specific bot, which could answer questions only specific to that particular enterprise where the questions are coming from. Technically this could be done with app-only access to SharePoint or Microsoft Graph, but we cannot expose this kind of WebAPI anonymously for Internet.
Any design patterns for this?
This is now possible, and I've actually even implemented it for Hubot in CoffeeScript and Node.JS. What I've described below is what it would look like in JavaScript/Node.JS.
Define an environment variable that, when set, filters for a particular tenant ID, OFFICE_365_TENANT_FILTER. (Doing it this way is a handy way of turning this feature on in production but not necessarily during development.)
For Microsoft Teams, the Office 365 tenant ID can be found here: session.message.sourceEvent.tenant.id.
The most elegant way to do it is to check for the tenant ID as middleware, and just drop further processing of the message if the filter is set and it doesn't match:
// [...]
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
var bot = new builder.UniversalBot(connector);
// Middleware to check for OFFICE_365_TENANT_FILTER and only continue processing if it matches.
// If OFFICE_365_TENANT_FILTER is not specified, do nothing.
bot.use({
botbuilder: function(session, next) {
var targetTenant = typeof(process.env.OFFICE_365_TENANT_FILTER) !== "undefined" ? process.env.OFFICE_365_TENANT_FILTER : null;
var currentMsgTenant = typeof(session.message.sourceEvent.tenant) !== "undefined" ? session.message.sourceEvent.tenant.id : null;
if (targetTenant !== null) {
if (targetTenant == currentMsgTenant) {
next();
}
else {
console.log("MS Teams: Attempted access from a different Office 365 tenant (" + currentMsgTenant + "): message rejected");
}
}
else {
next();
}
}
});
// [...]
Here's how to do this in C#, the SDK exposes the TenantFilter that allows you to add this action filter to the controller class as shown below.
using Microsoft.Bot.Connector.Teams;
namespace Microsoft.Teams.Samples.HelloWorld.Web.Controllers
{
[BotAuthentication, TenantFilter]
public class MessagesController : ApiController
{
[HttpPost]
public async Task<HttpResponseMessage> Post([FromBody] Activity activity)
The tenant filter will take a comma separated list of tenantIds that will need to be placed in the web.config
<configuration>
<appSettings>
<!--other settings-->
<add key="AllowedTenants" value="*TenantId1,TenantId2,...*"/>
Find your Office 365 tenant ID shows how you can do it through PowerShell.
It is not currently possible to know the tenant-id of the user chatting with the bot right away, unless the bot authenticates the user first. Please take a look at AuthBot. It illustrates how to send a sign-in link to a user and authenticate the user against AAD.
Although not exactly what you are looking for, you can create custom bots which will be scoped to individual Teams.
The security key/HMAC auth will prevent others from accessing the API. With the drawback that you will have to configure the bot with a separate security token for every Team where you want to use it.

Resources