Search code examples
c#botframeworkhttprequesthttp-status-code-401adaptive-dialogs

How to add Authentication token in HttpRequest in Adaptive dialog?


I am using Botframework adaptive dialog template (c#). I already obtained a token from a HttpRequest and saved it as a conversation state property conversation.token, now I am trying to use this token to make another API call with HttpRequest. But from the official document of HttpRequest Class, it seems there is no options to add the authentication token. I tried to add the token in the Headers, but did not work, it showed 401 Unauthorized error. How should the authorization be handled in HttpRequest in adaptive dialog?

new HttpRequest()
{
    Url = "http://example.com/json",
    ResultProperty = "conversation.httpResponse",
    Method = HttpRequest.HttpMethod.GET,
    ResponseType = HttpRequest.ResponseTypes.Json,
    Headers = new Dictionary<string, AdaptiveExpressions.Properties.StringExpression>()
    {
        {"Authorization", "Bearer ${conversation.token.content.token}"},
    },
},
new SendActivity("${conversation.httpResponse}"),

Solution

  • Instead of using HttpRequest, I made the API call inside CodeAction with custom code. First make a POST request to get the token, then make a GET request to call the main API. In the GET request, the authorization can be added in this way: client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);.

    new CodeAction(async (dc, options) =>
    {
        var my_jsondata = new
        {
            Username = "username",
            Password = "password"
        };
        var json = JsonConvert.SerializeObject(my_jsondata);
        var data = new StringContent(json, Encoding.UTF8, "application/json");
        var Tokenurl = "https://example.com/token?HTTP/1.1";
        using var Tokenclient = new HttpClient();
        var Tokenresponse = await Tokenclient.PostAsync(Tokenurl, data);
        string Toeknresult = Tokenresponse.Content.ReadAsStringAsync().Result;
        var Tokenjo = JObject.Parse(Tokenresult);
                                    
        using var client = new HttpClient();
        var url = "https://example.com/mainapi?HTTP/1.1";
        var accessToken = Tokenjo["token"];
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
        var response = await client.GetAsync(url);
        string result = response.Content.ReadAsStringAsync().Result;
                                   
        dc.State.SetValue("conversation.httpresponse", response);
        dc.State.SetValue("conversation.result", result);
    
        return await dc.EndDialogAsync();
    }),