You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BOT Directline Channel用户认证:Web应用对接Bot Framework技术问询

实现Direct Line WebChat的用户认证与身份安全传递

结合你提到的MVC Web应用场景,要确保已登录用户的信息能安全传递给机器人,同时避免Direct Line密钥泄露,核心思路是后端生成带用户身份的Direct Line Token,前端用Token连接机器人,具体步骤如下:

1. 后端生成带用户信息的Direct Line Token(关键!)

前端直接暴露Direct Line Secret风险极高,必须通过后端先验证用户登录状态,再生成包含用户身份的Token。以ASP.NET MVC为例:

using Microsoft.Bot.Connector.DirectLine;
using System.Security.Claims;

public async Task<ActionResult> Chat()
{
    // 先验证用户是否已登录(这里用ASP.NET Identity的方式,你可以换成自己的登录验证逻辑)
    if (!User.Identity.IsAuthenticated)
    {
        return RedirectToAction("Login", "Account");
    }

    // 从登录用户的Claims中获取真实身份信息
    string userId = User.Identity.Name;
    string userEmail = User.FindFirstValue(ClaimTypes.Email);

    // 初始化Direct Line客户端,使用你的Direct Line Secret(后端安全存储,不要暴露到前端)
    var directLineClient = new DirectLineClient("你的Direct Line Secret");
    
    // 生成带用户信息的会话Token
    var tokenResponse = await directLineClient.Tokens.GenerateTokenForNewConversationAsync(
        user: new ChannelAccount(id: userId, name: userEmail)
    );

    // 将Token传递给前端视图
    ViewBag.DirectLineToken = tokenResponse.Token;
    ViewBag.UserId = userId;
    ViewBag.UserEmail = userEmail;

    return View();
}

2. 前端WebChat使用Token初始化

在你的MVC视图中,用后端传递的Token替代Secret,同时同步用户信息:

BotChat.App({
    directLine: { token: '@ViewBag.DirectLineToken' },
    user: { id: '@ViewBag.UserId', email: '@ViewBag.UserEmail' },
    bot: { id: 'testBOT' },
    resize: 'detect'
}, document.getElementById("divbot"));

3. 机器人端接收并验证用户信息

机器人收到消息时,可从TurnContext.Activity.From中安全获取用户的身份信息(这些信息是后端生成Token时嵌入的,无法被前端篡改):

using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;

protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
    // 获取从后端传递过来的用户身份
    string userId = turnContext.Activity.From.Id;
    string userEmail = turnContext.Activity.From.Name;

    // 在这里可以结合业务逻辑使用用户信息,比如验证权限、关联用户数据等
    await turnContext.SendActivityAsync(MessageFactory.Text($"欢迎回来,{userEmail}!你的用户ID是:{userId}"), cancellationToken);
}

4. 额外安全加固

  • 启用Direct Line增强认证:在Azure Portal的Bot资源中,找到Direct Line通道的设置,开启「Require authentication for incoming activities」,这样机器人会自动验证Token的签名,确保用户信息未被篡改。
  • Token过期处理:Direct Line Token默认有效期是30分钟,你可以在后端生成时指定expiresIn参数延长有效期,或者在前端监听Token过期事件,调用后端接口刷新Token。

内容的提问来源于stack exchange,提问作者user2231

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:31:49