获取 403(禁止访问),Microsoft Bot 正在尝试进行 Web 客户端 - 下载数据调用

Getting 403 (Forbidden), Microsoft Bot is trying to make a Web Client - download data call

我正在尝试使用 Microsoft BotFramework

创建一个机器人

我面临的问题是当机器人代码试图通过 Facebook messenger/Skype/Slack 等任何渠道下载数据(用户上传到机器人的图像)时。要下载的代码是创建一个 WebClient 并通过传递附件 URL.

进行 DownloadData 调用

我可以浏览上传的图片URL。此外,如果我编写控制台应用程序而不是 Bot 应用程序,则通过 Web 客户端下载数据的代码工作正常。

c# 代码片段

WebClient wc = new WebClient(); 
byte[] bytes = wc.DownloadData(imageUrl); // This line gives 403 error

请提出解决此问题的建议。

这是问题的完整修复:

    private async Task<IEnumerable<byte[]>> GetAttachmentsAsByteArrayAsync(Activity activity)
    {
        var attachments = activity?.Attachments?
        .Where(attachment => attachment.ContentUrl != null)
        .Select(c => Tuple.Create(c.ContentType, c.ContentUrl));
        if (attachments != null && attachments.Any())
        {
            var contentBytes = new List<byte[]>();
            using (var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                var token = await (connectorClient.Credentials as MicrosoftAppCredentials).GetTokenAsync();
                foreach (var content in attachments)
                {
                    var uri = new Uri(content.Item2);
                    using (var httpClient = new HttpClient())
                    {
                        if (uri.Host.EndsWith("skype.com") && uri.Scheme == "https")
                        {
                            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
                        }
                        else
                        {
                            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(content.Item1));
                        }
                        contentBytes.Add(await httpClient.GetByteArrayAsync(uri));
                    }
                }
            }
            return contentBytes;
        }
        return null;
    }

https://github.com/Microsoft/BotBuilder/issues/662#issuecomment-232223965

你是说这个修复?这对你有用吗?

我在 Node.js 中使用 BotFramework 并收到相同的错误。 最后我找到了解决方法。我在 ChatConnector.js 中评论了以下几行,现在它对我来说工作正常。

if (isEmulator && decoded_1.payload.appid != this.settings.appId) {
       logger.error('ChatConnector: receive - invalid token. Requested by unexpected app ID.');
       res.status(403);
        res.end();
         return;
    }

if (isEmulator && decoded_1.payload.appid != this.settings.appId) { logger.error('ChatConnector: receive - invalid token. Requested by unexpected app ID.'); res.status(403); res.end(); return; }