从对话框到机器人类的身份验证令牌



我正在运行一个允许用户登录的OAuth对话框。我希望将此身份验证令牌从 DialogsClass.cs 获取到我的 Bot.Cs 类文件,并使用它来进行图形调用。

我尝试将令牌保存为字符串在我的对话框类中的本地文件中,然后在主机器人类中读回它,但这种解决方案似乎不是一种正确的方法。

身份验证对话框.cs在瀑布步骤中:

var tokenResponse = (TokenResponse)stepContext.Result;

预期成果。将此令牌从对话框类传输到 MainBot.cs 类,并用作字符串进行图形调用。

您是否使用一个瀑布步骤通过 OAuthPrompt 获取令牌,然后使用另一个步骤调用不同的类(在其中执行图形 API 调用)? 为什么不能将令牌传递给下游类?

如果中间还有其他步骤,有多种方法可以解决它:

  • 使用瀑布步骤上下文值
  • 保存到您自己的用户状态

>Microsoft建议不要在系统中存储令牌,而是调用oAuth提示符return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);并在必须调用图形 API 时获取最新令牌。收到令牌后var tokenResponse = (TokenResponse)stepContext.Result;您可以调用 GraphClient 类,该类将使用授权属性中的令牌创建图形 API 客户端。

var client = new GraphClientHelper(tokenResponse.Token);

图形客户端实现:

public GraphClientHelper(string token)
{
if (string.IsNullOrWhiteSpace(token))
{
throw new ArgumentNullException(nameof(token));
}
_token = token;
}
private GraphServiceClient GetAuthenticatedClient()
{
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
requestMessage =>
{
// Append the access token to the request.
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", _token);
// Get event times in the current time zone.
requestMessage.Headers.Add("Prefer", "outlook.timezone="" + TimeZoneInfo.Local.Id + """);
return Task.CompletedTask;
}));
return graphClient;
}

创建图形客户端后,可以调用所需的图形 api:

await client.CreateMeeting(meetingDetails).ConfigureAwait(false);

请参考此示例代码: 图形示例

最新更新