Integrating the Telegram Login Widget into an existing PHP application seems deceptively straightforward. When a user authenticates via Telegram's JavaScript widget or redirect flow, your backend receives a set of parameters over HTTP request variables: id, first_name, last_name, username, photo_url, auth_date, and hash.
If your backend code simply reads id from Yii::$app->request->get('id') and creates a logged-in user session, your authentication layer has a critical security flaw. Anyone can manually construct an HTTP GET request to your callback URL with an arbitrary id corresponding to another user or an administrator. Without cryptographic verification, your application accepts this parameter at face value, leading to immediate account takeover.
This guide details how to implement secure Telegram Login Widget verification in Yii2. You will construct a strict HMAC validation layer, enforce expiration windows on authentication timestamps, and safely attach verified telegram_id values to user models.
The Security Trap: Unverified Callback Parameters
Consider an endpoint handling the Telegram authorization redirect. The standard widget redirects the browser to your callback URL with query parameters appended to the request. A naïve controller action might look like this:
// DANGEROUS CODE - DO NOT USE IN PRODUCTION
public function actionTelegramCallback()
{
$telegramId = Yii::$app->request->get('id');
$user = User::findOne(['telegram_id' => $telegramId]);
if ($user) {
Yii::$app->user->login($user);
return $this->redirect(['/dashboard']);
}
// Register user...
}
Because HTTP GET requests can be executed by anyone with a web browser or curl, an attacker only needs to know an existing user's Telegram ID to log in as them.
Telegram mitigates this by supplying a hash parameter in the payload. This hash is a SHA-256 HMAC signature generated with a secret derived from your Telegram Bot Token. If the payload is modified, or if the request did not originate from Telegram's authorization servers, the signature check fails.
Furthermore, authenticating an incoming payload requires checking the auth_date parameter. An attacker who intercepts a valid set of callback parameters—including a correct hash—could replay that request days or months later to gain unauthorized access if your server does not check how old the signature is.
Cryptographic Validation: HMAC Check Implementation
The Telegram Login Widget signature algorithm works differently from Telegram Mini App (initData) validation. For the Login Widget, the secret key is the raw SHA-256 hash of your bot token. For Mini Apps, the secret key uses a keyed HMAC with the constant string WebAppData. Confusing these two verification schemes will cause all signature checks to fail.
To verify a Login Widget signature:
1. Filter out the hash parameter from the incoming request key-value pairs. 2. Sort the remaining key-value pairs alphabetically by key. 3. Form a newline-delimited data-check string where each line contains key=value. 4. Generate a secret key by taking the SHA-256 hash of your raw Bot Token in binary format (hash('sha256', $botToken, true)). 5. Compute the HMAC-SHA256 signature of the data-check string using the generated secret key. 6. Compare your computed hex signature against the hash parameter supplied in the request using a constant-time string comparison function (hash_equals).
Create a reusable component inside your Yii2 application to encapsulate this security logic:
namespace app\components;
use yii\base\Component;
use yii\base\InvalidArgumentException;
class TelegramLoginValidator extends Component
{
/**
* @var string Your Telegram Bot Token obtained from @BotFather
*/
public string $botToken;
/**
* @var int Maximum allowed age of auth_date in seconds (default: 86400 = 24h)
*/
public int $maxAuthAge = 86400;
public function init(): void
{
parent::init();
if (empty($this->botToken)) {
throw new InvalidArgumentException('Bot token must be configured.');
}
}
/**
* Validates incoming array of parameters from Telegram Login Widget.
*
* @param array $authData Key-value pairs from request GET/POST
* @return bool True if verification succeeds, false otherwise
*/
public function validate(array $authData): bool
{
if (!isset($authData['hash'], $authData['auth_date'])) {
return false;
}
$checkHash = $authData['hash'];
unset($authData['hash']);
// Step 1: Verify auth_date freshness
$authDate = (int)$authData['auth_date'];
if ((time() - $authDate) > $this->maxAuthAge) {
return false;
}
// Step 2: Build the data-check string
$dataCheckArray = [];
foreach ($authData as $key => $value) {
$dataCheckArray[] = $key . '=' . $value;
}
sort($dataCheckArray);
$dataCheckString = implode("
", $dataCheckArray);
// Step 3: Compute secret key and HMAC
$secretKey = hash('sha256', $this->botToken, true);
$hash = hash_hmac('sha256', $dataCheckString, $secretKey);
// Step 4: Timing-attack safe comparison
return hash_equals($hash, $checkHash);
}
}
Database Schema and Migration
Before tying Telegram accounts to local identity records, construct a database migration to store the unique telegram_id string alongside existing user accounts. The telegram_id column must be indexed and marked as unique to avoid account mapping collisions.
Run the following code via Yii2 console migrations (yii migrate/create add_telegram_id_to_user_table):
use yii\db\Migration;
class m240101_000000_add_telegram_id_to_user_table extends Migration
{
public function safeUp(): void
{
$this->addColumn('{{%user}}', 'telegram_id', $this->bigInteger()->unsigned()->null()->unique());
$this->createIndex('idx-user-telegram_id', '{{%user}}', 'telegram_id');
}
public function safeDown(): void
{
$this->dropIndex('idx-user-telegram_id', '{{%user}}');
$this->dropColumn('{{%user}}', 'telegram_id');
}
}
Using a bigInteger data type is required because Telegram user IDs have expanded beyond 32-bit signed integer limits.
Integrating Telegram Authentication into a Yii2 Controller
With the validator component and database schema ready, implement the authentication flow in a dedicated controller. The flow supports two distinct business cases:
1. Logging in an existing user whose telegram_id is already matched. 2. Linking a verified telegram_id to an existing authenticated user session.
Configure the validator as a component in config/web.php or instantiate it dynamically inside the action. Reading the bot token from environment variables ensures sensitive API keys are not leaked into source control:
// config/web.php
'components' => [
'telegramValidator' => [
'class' => 'app\components\TelegramLoginValidator',
'botToken' => getenv('TELEGRAM_BOT_TOKEN'),
'maxAuthAge' => 3600, // 1 hour expiration threshold
],
],
The unified action handles the payload, executes the HMAC check, and manages session state securely:
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\web\BadRequestHttpException;
use yii\web\UnauthorizedHttpException;
use app\models\User;
class AuthController extends Controller
{
public function actionTelegramCallback()
{
$request = Yii::$app->request;
$params = $request->get();
/** @var \app\components\TelegramLoginValidator $validator */
$validator = Yii::$app->telegramValidator;
// Reject invalid signatures or expired auth_date payloads
if (!$validator->validate($params)) {
throw new UnauthorizedHttpException('Invalid or expired Telegram authentication payload.');
}
$telegramId = (int)$params['id'];
$currentUser = Yii::$app->user;
// Scenario A: User is already logged in, bind Telegram account
if (!$currentUser->isGuest) {
$user = User::findOne($currentUser->id);
// Prevent taking over an ID bound to another identity
$existingBoundUser = User::findOne(['telegram_id' => $telegramId]);
if ($existingBoundUser && $existingBoundUser->id !== $user->id) {
throw new BadRequestHttpException('This Telegram account is already linked to another user.');
}
$user->telegram_id = $telegramId;
$user->save(false, ['telegram_id']);
Yii::$app->session->setFlash('success', 'Telegram account linked successfully.');
return $this->redirect(['/user/profile']);
}
// Scenario B: Guest user logging in via Telegram
$user = User::findOne(['telegram_id' => $telegramId]);
if ($user) {
Yii::$app->user->login($user, 3600 * 24 * 30); // 30 days session
return $this->goBack();
}
// Scenario C: First time login — optional auto-registration or flow redirect
Yii::$app->session->setFlash('error', 'No user account found linked to this Telegram ID.');
return $this->redirect(['/site/login']);
}
}
Front-End Integration: Embedding the Telegram Widget
To trigger this process from the client side, render the Telegram Embed JS snippet inside your Yii2 view template. Set data-auth-url to target your newly created controller action:
<?php
use yii\helpers\Url;
?>
<div class="telegram-login-container">
<h3>Sign in with Telegram</h3>
<script
async
src="https://telegram.org/js/telegram-widget.js?22"
data-telegram-login="YourBotUsername"
data-size="large"
data-radius="8"
data-auth-url="<?= Url::to(['auth/telegram-callback'], true) ?>"
data-request-access="write">
</script>
</div>
When users complete authentication inside the modal popup, Telegram automatically appends the user details and signature hash to your data-auth-url before redirecting the browser.
Production Notes
- Clock Skew Management: Differences between your server clock and Telegram's authentication servers can cause valid authorizations to fail if your $maxAuthAge window is set too low. Ensure NTP (Network Time Protocol) is active on your host server. Allow a minimum age window of at least 300 seconds (5 minutes) to avoid rejecting valid signatures during minor server drift. - Strict Data Types: Convert the incoming auth_date and id parameters to integers explicitly when processing. Loose comparisons or implicit string parsing can lead to verification failures when constructing the data_check_string. - Timing Attack Mitigation: Never use standard string comparison ($a === $b) to validate cryptographically generated hashes. Always use PHP’s built-in hash_equals() function, which executes in constant time to prevent side-channel timing analysis attacks. - Differentiating Login Widget vs Mini App auth: Remember that Telegram Mini Apps transmit authorization credentials formatted as an URL-encoded string (initData) requiring a key derivation step using WebAppData as the HMAC key. The Login Widget described in this guide supplies distinct query parameters directly, using the SHA-256 hash of the bot token directly as the key. Mixing these algorithms will fail validation.
Building custom integrations between web platforms and Telegram messaging environments requires precision in authentication flow security and cryptographic handling. For teams building specialized implementations or expanding into automated workflows, BotCreator is a studio that ships Telegram bots and Mini Apps.