Search code examples
authenticationbotsbotframeworkdirect-line-botframework

How can I send my userID an Token from my client to the Bot through direct line in Microsoft Bot Framework


I have a client that authenticated through log in, I need to pass that userId and token to the bot in every request so that I can use that to hit my server Web api which requires this info. I tried getting the Authorization that comes in the header but it carries the Secret. It would work for me if I could attach id and token to the header.

this.botConnection = new BotChat.DirectLine({
    secret: 'yNy9g1Mok1g.cwA.fyks.fghsth.rcKOQUIu558-TI',//params['mysecret'], 
    token: params[this.token],     //I think I should pass it here but this does not work.
  //domain: params['ngroktunneledurl.com/api/messages'],
    webSocket: params['webSocket'] && params['webSocket'] === "true" // defaults to true,
});

Then FROM the bot trying to retrieve the token in the message Controller..

    public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
    {

        if (activity.Type == ActivityTypes.Message)
        {
          var keyValuePair = Request.Headers.FirstOrDefault(h => h.Key.Equals("Authorization"));
          token = keyValuePair.Value.First().Substring(7);

           await Conversation.SendAsync(activity, () => new Dialogs.RootDialog(token));
        }
        else
        {
            HandleSystemMessage(activity).ConfigureAwait(false);
        }
        var response = Request.CreateResponse(HttpStatusCode.OK);
        return response;
    }

Authorization brings the Secret that identifies our bot.


Solution

  • I was able to achieve this by sending an activity to the bot which contains the values I need to send. I only had to deserialize the object to get its value from the c# code afterwards.

    BotChat.App({
            botConnection:
            {
                ...dl,
                postActivity: activity => {
                    // Add some custom data
                    activity.channelData.MyKey = this.Id;
                    activity.channelData.token = this.token;
                    return dl.postActivity(activity)
                }
            },
              user: user,
              bot: bot
          }, document.getElementById("BotChatGoesHere"))