Telegram Login Widget in PHP and Yii2: HMAC-SHA-256, auth_date Verification, and Account Linking

Виджет авторизации Telegram (Login Widget) allows users to log in to a website in one click without entering passwords or SMS codes. However, the data set passed by the client (id, name, username, auth_date) is open to spoofing. The only way to make sure the data came from Telegram and not from Postman or a fake form is backend HMAC-SHA-256 signature validation.

In this article, we will examine in detail the Login Widget signature verification algorithm, the nuances of working with the auth_date timestamp, and write a clean PHP validator alongside a ready-to-use Yii2 controller that handles registration, login, and Telegram account linking.

How Telegram Login Widget Works and What's the Catch

When a user clicks the login button via the widget, Telegram redirects them to your redirect_url with a set of parameters in GET or sends a JS object to the callback. The data array has the following format:

  • id — unique Telegram user identifier;
  • first_name, last_name, username, photo_url — profile data;
  • auth_date — Unix timestamp of the authorization time;
  • hash — final hash sum for validity check.

The main mistake of developers: confusing the hashing algorithm of Telegram Login Widget and Telegram Mini Apps (initData). In Mini Apps, the secret key is HMAC-SHA-256("WebAppData", bot_token). In the Login Widget, the secret key is generated as a regular binary SHA-256 of the bot token: hash('sha256', bot_token, true).

HMAC-SHA-256 Signature Verification Algorithm in PHP

To verify the authenticity of the received data, you need to replicate the Telegram algorithm on the server:

  1. Extract the hash parameter from the array of received data.
  2. Remove hash from the array so it is not included in string generation.
  3. Sort the remaining key-value pairs alphabetically by keys.
  4. Form the string-to-sign (data_check_string) by concatenating elements in the format key=value separated by newline characters .
  5. Calculate the binary SHA-256 hash of the bot token.
  6. Compute HMAC-SHA-256 of the generated string using the binary key.
  7. Compare the calculated hash with the provided hash using the hash_equals() function to protect against timing attacks.

Below is an isolated service class for PHP 8.x implementing this logic and additionally checking the authorization age via auth_date.

<?php

namespace app\components;

final class TelegramWidgetValidator
{
private string $botToken;
private int $maxAge;

public function __construct(string $botToken, int $maxAge = 86400)
{
$this->botToken = $botToken;
$this->maxAge = $maxAge;
}

public function validate(array $authData): bool
{
if (empty($authData['hash']) || empty($authData['auth_date'])) {
return false;
}

$checkHash = (string)$authData['hash'];
unset($authData['hash']);

// Защита от replay-атак: проверяем age таймштампа
$authDate = (int)$authData['auth_date'];
if ((time() - $authDate) > $this->maxAge) {
return false;
}

$dataCheckArray = [];
foreach ($authData as $key => $value) {
$dataCheckArray[] = $key . '=' . $value;
}

sort($dataCheckArray);
$dataCheckString = implode("
", $dataCheckArray);

$secretKey = hash('sha256', $this->botToken, true);
$calculatedHash = hash_hmac('sha256', $dataCheckString, $secretKey);

return hash_equals($calculatedHash, $checkHash);
}
}

Replay Attack Protection: Why auth_date Is Needed

The hash value guarantees that the user data was not altered in transit. However, without checking auth_date, an attacker who intercepts a valid URL with parameters once could log in under someone else's name indefinitely.

Checking (time() - $authDate) > $this->maxAge ensures that raw authorization data is valid for only a limited time (for example, 86400 seconds = 24 hours). If the request is older than a day, the backend rejects authorization and prompts for re-login.

Implementing Authorization and Account Linking in Yii2

Let's consider the workflow of a Yii2 controller upon receiving a redirect from the Telegram Login Widget. We support 3 main scenarios:

  • The user already exists in the database — perform session log-in.
  • The user is already logged in with a standard account on the site — link telegram_id to it.
  • The user is new — create a new account and log in.
<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;
use app\models\User;
use app\components\TelegramWidgetValidator;

class AuthController extends Controller
{
public function actionTelegramCallback(): Response
{
$request = Yii::$app->request;
$authData = $request->get();

$botToken = Yii::$app->params['telegramBotToken'] ?? getenv('TELEGRAM_BOT_TOKEN');
if (!$botToken) {
throw new \RuntimeException('Токен Telegram бота не задан в конфигурации.');
}

$validator = new TelegramWidgetValidator($botToken, 86400);

if (!$validator->validate($authData)) {
Yii::$app->session->setFlash('error', 'Ошибка безопасности: недействительная подпись Telegram.');
return $this->redirect(['site/login']);
}

$telegramId = (int)$authData['id'];
$user = User::findOne(['telegram_id' => $telegramId]);

// 1. Пользователь с таким telegram_id уже есть — входим
if ($user !== null) {
Yii::$app->user->login($user, 3600 * 24 * 30);
return $this->goHome();
}

// 2. Пользователь уже авторизован на сайте — привязываем Telegram к профилю
if (!Yii::$app->user->isGuest) {
/** @var User $currentUser */
$currentUser = Yii::$app->user->identity;
$currentUser->telegram_id = $telegramId;
$currentUser->telegram_username = $authData['username'] ?? null;

if ($currentUser->save(false)) {
Yii::$app->session->setFlash('success', 'Telegram-аккаунт успешно привязан.');
}
return $this->redirect(['user/profile']);
}

// 3. Новый пользователь — регистрируем
$newUser = new User();
$newUser->telegram_id = $telegramId;
$newUser->username = $authData['username'] ?? ('tg_' . $telegramId);
$newUser->first_name = $authData['first_name'] ?? '';
$newUser->last_name = $authData['last_name'] ?? '';
$newUser->auth_key = Yii::$app->security->generateRandomString();

if ($newUser->save(false)) {
Yii::$app->user->login($newUser, 3600 * 24 * 30);
$this->sendTelegramNotification($telegramId, "Вы успешно вошли на сайт через Telegram Widget!");
return $this->goHome();
}

Yii::$app->session->setFlash('error', 'Не удалось создать пользователя.');
return $this->redirect(['site/login']);
}

private function sendTelegramNotification(int $chatId, string $message): bool
{
$botToken = Yii::$app->params['telegramBotToken'] ?? getenv('TELEGRAM_BOT_TOKEN');
$url = "https://api.telegram.org/bot{$botToken}/sendMessage";

$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'chat_id' => $chatId,
'text' => $message,
'parse_mode' => 'HTML',
]),
CURLOPT_TIMEOUT => 5,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($response === false || $httpCode !== 200) {
return false;
}

$result = json_decode($response, true);
return json_last_error() === JSON_ERROR_NONE && !empty($result['ok']);
}
}

Configuring the Widget on the Frontend

Insert the following JS script on your website's authorization page. Replace bot_name with your bot's username without the @ symbol, and data-auth-url with the absolute URL of your Yii2 action.

<script async src="https://telegram.org/js/telegram-widget.js?22" 
data-telegram-login="YourProjectBot"
data-size="large"
data-auth-url="https://example.com/auth/telegram-callback"
data-request-access="write">
</script>

Common Mistakes When Working with Telegram Login Widget

  • Using file_get_contents for API: All requests to api.telegram.org should be made via cURL with explicit checks for HTTP status code and JSON parsing errors.
  • Comparing strings with === instead of hash_equals(): Regular comparison using the === operator is vulnerable to timing attacks based on byte comparison. Always use hash_equals().
  • Data mutation before verification: Ensure parameters from $_GET are passed to the validator in their original string form without prior forced typecasting.
  • Linking without authorization: When linking accounts, always check the current session status (!Yii::$app->user->isGuest) to prevent unauthorized takeover of another user's profile.

Developing and integrating complex solutions based on Telegram Bot API requires a deep understanding of security and architecture — you can entrust such a task to a specialized team at the BotCreator service.

New articles on Telegram

We explain what to automate in your business and how it works in practice. No spam.