首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Azure Web聊天Bot令牌服务器

Azure Web聊天Bot令牌服务器
EN

Stack Overflow用户
提问于 2020-01-17 07:22:00
回答 1查看 911关注 0票数 1

问题是:

我在努力想办法弄到代币。我知道我为什么要用它们,但我只是不知道如何得到它们。所有使用令牌的示例只需从"https://webchat-mockbot.azurewebsites.net/directline/token“或类似的东西中获取它们。如何在我的机器人中创建这条路径?

描述了您已经考虑过的替代方案

我创造了一些和我的JS一起工作的东西:

代码语言:javascript
复制
    const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function() {
    console.log(`\n${ server.name } listening to ${ server.url }`);
    console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator');
    console.log('\nTo talk to your bot, open the emulator select "Open Bot"');
});

server.post('/token-generate', async (_, res) => {
  console.log('requesting token ');
  try {
    const cres = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', {
      headers: { 
        authorization: `Bearer ${ process.env.DIRECT_LINE_SECRET }`
      },
      method: 'POST'
    });

    const json = await cres.json();


    if ('error' in json) {
      res.send(500);
    } else {
      res.send(json);
    }
  } catch (err) {
    res.send(500);
  }
});

但是我找不到如何用我的C#-Bot来完成这个任务(我改用了C#,因为我比JS更了解它)。

在我的C#-Bot中只有这样:

代码语言:javascript
复制
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.AspNet.Core;

namespace ComplianceBot.Controllers
{
    // This ASP Controller is created to handle a request. Dependency Injection will provide the Adapter and IBot
    // implementation at runtime. Multiple different IBot implementations running at different endpoints can be
    // achieved by specifying a more specific type for the bot constructor argument.
    [Route("api/messages")]
    [ApiController]
    public class BotController : ControllerBase
    {
        private readonly IBotFrameworkHttpAdapter _adapter;
        private readonly IBot _bot;

        public BotController(IBotFrameworkHttpAdapter adapter, IBot bot)
        {
            _adapter = adapter;
            _bot = bot;
        }

        [HttpGet, HttpPost]
        public async Task PostAsync()
        {
            // Delegate the processing of the HTTP POST to the adapter.
            // The adapter will invoke the bot.
            await _adapter.ProcessAsync(Request, Response, _bot);
        }
    }
}

我能在这里增加一条新路线吗?比如路线(“直接线路/令牌”)?

我知道我可以用一个额外的“令牌服务器”(我不知道如何实现它,但我知道这是可行的),但如果可能的话,我想用我已经存在的c#-机器人,就像我对我的JS那样。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-17 09:38:07

我已经发布了一个答案,其中包括如何在C# bot中实现API以获得直接行访问令牌,以及如何获得此令牌,请参考这里。如果您还有其他问题,请随时通知我。

最新情况:

我的代码是基于这个演示的。如果您使用的是.net核心,请在/Controllers文件夹下创建一个TokenController.cs

TokenController.cs代码:

代码语言:javascript
复制
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Microsoft.BotBuilderSamples.Controllers
{

    [Route("api/token")]
    [ApiController]
    public class TokenController : ControllerBase
    {


        [HttpGet]
        public async Task<ObjectResult> getToken()
        {
            var secret = "<direct line secret here>";

            HttpClient client = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage(
                HttpMethod.Post,
                $"https://directline.botframework.com/v3/directline/tokens/generate");

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secret);

            var userId = $"dl_{Guid.NewGuid()}";

            request.Content = new StringContent(
                Newtonsoft.Json.JsonConvert.SerializeObject(
                    new { User = new { Id = userId } }),
                    Encoding.UTF8,
                    "application/json");

            var response = await client.SendAsync(request);
            string token = String.Empty;

            if (response.IsSuccessStatusCode)
            {
                var body = await response.Content.ReadAsStringAsync();
                token = JsonConvert.DeserializeObject<DirectLineToken>(body).token;
            }

            var config = new ChatConfig()
            {
                token = token,
                userId = userId
            };

            return Ok(config);
        }
    }
    public class DirectLineToken
    {
        public string conversationId { get; set; }
        public string token { get; set; }
        public int expires_in { get; set; }
    }
    public class ChatConfig
    {
        public string token { get; set; }
        public string userId { get; set; }
    }
}

将机密替换为您自己的直接线路机密后运行该项目。您将能够通过本地的url:http://localhost:3978/api/token获得令牌:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59782810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档