[Telegram] System.UnauthorizedAccessException for bot-initiated connection to https://telegram.botframework.com
Hi, I have faced really weird issue
When the bot had started, I sent a message to it via skype; due to the logic of the bot it tried to send a message via telegram to contact, that contacted a bot earlier (before this launch).
As a result I got the following exception
{
"ClassName": "System.UnauthorizedAccessException",
"Message": "Authorization for Microsoft App ID *** failed with status code Forbidden",
...
}
The connector was created by the following code
_connector = new ConnectorClient(new Uri(apiEndpoint));
where apiEndpoint is a string, saved during the previous launch, and it equals to "https://telegram.botframework.com"
The message was created "from scratch" by pre-saved apiEndpoint and id of recipient
{
"type": "message",
"serviceUrl": "https://telegram.botframework.com",
"channelId": "telegram",
"from": {
"id": "devexbot",
"name": "devex"
},
"conversation": {
"isGroup": false,
"id": "295410140"
},
"recipient": {
"id": "295410140"
},
"text": ***
}
The most interesting thing, that when I contacted the same bot via telegram within this launch of the bot, the same code worked and the message was sent and delivered properly, so to provide proper functionality of the bot I have to contact it with telegram after each service launch
@akakoychenko are you using C# or Node SDK?
C#
I have inspected the behaviour of the bot with Fiddler and found out the headers of requests to https://telegram.botframework.com before and after first telegram user-initiated contact are different
Bot-initiated request after user-initiated message has the header
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJ...
when bot-initiated requests before user-initiated message don't have it
The responses are different too. It is HTTP/1.1 200 OK for request with this header and HTTP/1.1 401 Unauthorized for request without it.
I have solved the issue on the local copy of the Bot.Connector sources by making the following function "always true" (MicrosoftAppCredentials.cs, line 185)
private bool ShouldSetToken(HttpRequestMessage request)
{
return true;
if (TrustedUri(request.RequestUri))
{
return true;
}
#if NET45
Trace.TraceWarning($"Service url {request.RequestUri.Authority} is not trusted and JwtToken cannot be sent to it.");
#else
logger?.LogWarning($"Service url {request.RequestUri.Authority} is not trusted and JwtToken cannot be sent to it.");
#endif
return false;
}