[英]How to add Authentication token in HttpRequest in Adaptive dialog?
I am using Botframework adaptive dialog template (c#).我正在使用 Botframework 自适应对话框模板(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.我已经从 HttpRequest 获得了一个令牌并将其保存为会话 state 属性conversation.token
.token ,现在我正在尝试使用此令牌与 HttpRequest 进行另一个 API 调用。 But from the official document of HttpRequest Class , it seems there is no options to add the authentication token.但是从HttpRequest Class的官方文档来看,似乎没有添加身份验证令牌的选项。 I tried to add the token in the Headers, but did not work, it showed 401 Unauthorized error.我尝试在 Headers 中添加令牌,但没有成功,它显示401 Unauthorized错误。 How should the authorization be handled in HttpRequest in adaptive dialog?自适应对话框中的 HttpRequest 应该如何处理授权?
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}"),
Instead of using HttpRequest, I made the API call inside CodeAction with custom code.我没有使用 HttpRequest,而是使用自定义代码在 CodeAction 中调用了 API。 First make a POST request to get the token, then make a GET request to call the main API.先发出POST请求获取token,然后发出GET请求调用主API。 In the GET request, the authorization can be added in this way: client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
在GET请求中,可以这样添加授权: 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();
}),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.