Azure 网络聊天机器人令牌服务器 [英] Azure Web Chat Bot Token Server

查看:39
本文介绍了Azure 网络聊天机器人令牌服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

我正在努力了解如何获取令牌.我知道为什么我应该使用它们,但我就是不明白如何获得它们.所有使用令牌的示例都只是从 "

TokenController.cs 的代码:

使用系统;使用 System.Net.Http;使用 System.Net.Http.Headers;使用 System.Text;使用 System.Threading.Tasks;使用 Microsoft.AspNetCore.Mvc;使用 Newtonsoft.Json;命名空间 Microsoft.BotBuilderSamples.Controllers{[路由(API/令牌")][API控制器]公共类 TokenController : ControllerBase{[HttpGet]公共异步任务获取令牌(){var secret = "<这里的直线秘密>";HttpClient 客户端 = 新的 HttpClient();HttpRequestMessage 请求 = 新的 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 } }),编码.UTF8,应用程序/json");var response = await client.SendAsync(request);字符串令牌 = String.Empty;如果(响应.IsSuccessStatusCode){var body = await response.Content.ReadAsStringAsync();token = JsonConvert.DeserializeObject(body).token;}var config = new ChatConfig(){令牌=令牌,用户 ID = 用户 ID};返回确定(配置);}}公共类 DirectLineToken{公共字符串conversationId { 获取;放;}公共字符串令牌 { 获取;放;}公共 int expires_in { 得到;放;}}公共类 ChatConfig{公共字符串令牌 { 获取;放;}公共字符串用户 ID { 获取;放;}}}

在用您自己的直线密码替换密码后运行项目.您将能够通过 url 获取令牌:http://localhost:3978/api/token on local :

The Problem:

I am struggeling to understand how to get tokens. I know why I should use them, but I just don't understand how to get them. All the samples that uses Tokens just fetch them from "https://webchat-mockbot.azurewebsites.net/directline/token" or something similar. How do I create this path in my bot?

Describe alternatives you have considered

I was able to create something which worked with my JS-Bot:

    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);
  }
});

But I don't find how to do this with my C#-Bot ( I switched to C# because I understand it better than JS).

In my C#-Bot there is only this:

// 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);
        }
    }
}

Can I add a new Route here? like [Route("directline/token")] ?

I know I could do this with an extra "token-server" (I don't know how to realise it, but I know that would work), but if possible I'd like to do this with my already existing c#-bot as I did it with my JS-Bot.

解决方案

I have posted an answer which includes how to implement an API to get a direct line access token in C# bot and how to get this token, just refer to here. If you have any further questions, pls feel free to let me know .

Update :

My code is based on this demo . If you are using .net core, pls create a TokenController.cs under /Controllers folder:

Code of TokenController.cs :

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; }
    }
}

Run the project after you replace secret with your own direct line secret. You will be able to get token by url: http://localhost:3978/api/token on local :

这篇关于Azure 网络聊天机器人令牌服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆