Search code examples
telegramtelegram-bottelegram-webhooktelegram-api

How verify request of webhook are from Telegram?


I have a Telegram bot that is set to work with Telegram webhook mechanism but how trust requests and know if they are from Telegram?

base on Telegram docs I find out there is two way:

  • limit them to telegam ip (this is dirty, if for some reason telegam change its ip my bot will shut down so it is not a option)
  • set a private long url for webhook so only my server and telegram know the url (I don't think it's a good enough solution to secure my webhook, urls are public if for some reason my url leak, everyone can pretend they are telegram and send fake requests)

these two was what I found is there anything I miss? why Telegram don't provide a rsa public key like OAuth2 or some trusted token or signature like Github for its webhook? is private url enough for security?


Solution

  • As of Bot API 6.1, there is a new optional secret_token string parameter to the setWebhook method:

    A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you.

    So you would pass this parameter when setting the webhook, then on each incoming request you would verify that the X-Telegram-Bot-Api-Secret-Token header matches.