Authentication overview

Telegraph, powered by the Telegram API, uses distinct authentication mechanisms depending on whether the interaction is from a user client or a bot. The core Telegram API, known as MTProto, is a custom-built protocol designed for secure and efficient mobile messaging. This protocol handles the cryptographic challenges of user authentication and data exchange for official and third-party Telegram client applications Telegram API authentication overview. For automated services, the Telegram Bot API provides a simpler, token-based authentication method, allowing developers to create bots that interact with Telegram users and chats Telegram Bot API documentation.

The MTProto Mobile Protocol employs a combination of Diffie-Hellman key exchange for establishing secure session keys, followed by AES256 for symmetric encryption of messages MTProto specification details. This multi-layered approach aims to ensure that communications between clients and Telegram servers are protected against eavesdropping and tampering. Bot API authentication, while leveraging Telegram's secure infrastructure, simplifies the developer experience by relying on a unique token that identifies the bot and grants it specific permissions.

Supported authentication methods

Telegraph's underlying API supports two primary authentication methods tailored to different use cases:

Method When to Use Security Level
MTProto API (Client Applications) Developing custom Telegram clients, full user account access, and advanced messaging features. Requires handling cryptographic primitives and session management. High: End-to-end encryption for Secret Chats, strong client-server encryption for all communications using Diffie-Hellman key exchange and AES256. RFC 3526 on Diffie-Hellman.
Bot API (Bot Applications) Creating automated bots for tasks, notifications, chat management, and integrations. Simpler to implement than MTProto. Moderate-High: Communication between your bot server and Telegram's Bot API is secured via HTTPS. The bot token acts as the primary credential, requiring secure handling.

For MTProto, the authentication process typically involves several steps:

  1. Exchanging Public Keys: The client and server exchange public keys to establish a shared secret.
  2. Generating Session Keys: A session key is derived from the shared secret using a Diffie-Hellman key exchange Mozilla Diffie-Hellman explanation.
  3. Sending Authorization Key: The client encrypts an authorization key with the session key and sends it to the server.
  4. User Login: The user provides their phone number and a one-time code received via SMS or through the Telegram app to verify their identity.

The Bot API, in contrast, streamlines this by providing a single, unique token for each bot. This token is included in every API request, authenticating the bot and authorizing its actions within the scope of its permissions.

Getting your credentials

The process for obtaining credentials varies significantly between MTProto API client development and Bot API bot development:

For MTProto API (Custom Clients):

To develop a custom Telegram client using the MTProto API, you need an API ID and an API Hash. These credentials identify your application to the Telegram servers:

  1. Register your application: Visit the Telegram API Development Tools page.
  2. Provide details: Enter your phone number (associated with your Telegram account), confirmation code, app title, and short name.
  3. Receive credentials: Upon successful registration, you will be provided with an api_id and api_hash. These are crucial for initializing your MTProto client library.

The api_id is a public identifier for your application, while the api_hash is a secret key that should be kept confidential. These credentials allow your client to connect to Telegram's service and authenticate user sessions.

For Bot API (Bots):

To create a bot and obtain its authentication token, you interact directly with Telegram via another bot, the BotFather:

  1. Open Telegram: Search for the official @BotFather bot.
  2. Start a new bot: Send the /newbot command to BotFather.
  3. Follow prompts: BotFather will ask for a name and a username for your bot.
  4. Receive token: After successfully creating the bot, BotFather will provide you with an HTTP API token. This is a long string of alphanumeric characters, e.g., 123456:ABC-DEF1234ghIkl-789_jklmnop.

This token is your bot's credential and must be kept secure. Any person with access to this token can control your bot. You can revoke and regenerate a bot token at any time via BotFather using the /revoke command.

Authenticated request example

For the Telegram Bot API, authenticated requests are straightforward and involve including the bot token in the URL path. Here's an example of sending a message using the Bot API's sendMessage method:

POST https://api.telegram.org/bot<YOUR_BOT_TOKEN>/sendMessage
Content-Type: application/json

{
  "chat_id": "@my_channel_username",
  "text": "Hello from my Telegram bot!"
}

Replace <YOUR_BOT_TOKEN> with the actual token obtained from BotFather. The chat_id can be a user's ID, a group chat ID, or a channel username (prefixed with @).

For MTProto API, the process is more complex due to the underlying protocol and cryptography. Developers typically use existing libraries or SDKs that abstract away the low-level MTProto details. Here's a conceptual Python example using a hypothetical MTProto client library, demonstrating how an authenticated session might be established and used:

from my_mtproto_library import MTProtoClient

API_ID = 1234567
API_HASH = "your_api_hash_here"
PHONE_NUMBER = "+12345678900"

client = MTProtoClient(api_id=API_ID, api_hash=API_HASH)

async def main():
    await client.connect()

    if not await client.is_user_authorized():
        await client.send_code_request(PHONE_NUMBER)
        # User receives a code, enters it
        code = input("Enter the code you received: ")
        await client.sign_in(PHONE_NUMBER, code)

    # Now the client is authenticated and can make requests
    # Example: get information about the authenticated user
    me = await client.get_me()
    print(f"Authenticated as: {me.first_name} {me.last_name} (@{me.username})")

    await client.disconnect()

# Run the async function
# import asyncio
# asyncio.run(main())

This example illustrates the multi-step process for MTProto, where explicit code requests and sign-in steps are required to establish an authenticated user session. The underlying library handles the MTProto protocol's cryptographic handshakes and session management Telegram API session management.

Security best practices

Adhering to security best practices is essential for protecting both your application and user data when interacting with the Telegraph API:

  • Securely Store API Credentials: Never hardcode API IDs, API Hashes, or Bot Tokens directly into your source code. Use environment variables, secure configuration files, or a secrets management service to store these credentials.
  • Restrict Bot Permissions: When creating a bot, only grant it the minimum necessary permissions. Use BotFather's /setcommands and /setprivacy features to control what your bot can do and what messages it can see BotFather capabilities.
  • Use HTTPS for Bot API Calls: Always ensure that your bot makes requests to the Telegram Bot API over HTTPS to encrypt the communication channel and prevent token interception. This is the default for api.telegram.org.
  • Validate Webhook Signatures: If your bot uses webhooks to receive updates, validate the X-Telegram-Bot-Api-Secret-Token header to ensure that the requests originate from Telegram and not a malicious source Telegram Bot API webhook documentation.
  • Implement Rate Limiting: Protect your bot and Telegram's infrastructure by implementing proper rate limiting. Excessive API calls can lead to temporary bans or service degradation.
  • Regularly Rotate Bot Tokens: If you suspect a bot token has been compromised, or as part of a routine security policy, use BotFather's /revoke command to invalidate the old token and generate a new one.
  • Protect User Data: If your custom client or bot handles user data, ensure compliance with relevant data protection regulations (e.g., GDPR, CCPA). Only request and store data that is strictly necessary for your application's functionality.
  • Secure Client Environments: For MTProto clients, ensure the environment where your API ID and API Hash are used is secure. Protect the client application from reverse engineering or unauthorized access that could expose these secrets.
  • Keep Dependencies Updated: Regularly update any third-party libraries or SDKs used for interacting with the Telegram API to patch known vulnerabilities.