Skip to main content

django-telegram-auth

django-telegram-auth is a small Django REST Framework package for authenticating API requests that come from Telegram integrations.

It provides:

  • Authentication for Telegram Web App initData
  • Authentication for trusted bot API requests using DRF tokens
  • Permission classes for Telegram-authenticated users
  • A reusable service for validating and parsing Telegram Web App payloads

Requirements

  • Python 3.9+
  • Django
  • Django REST Framework
  • rest_framework.authtoken for bot API authentication

Installation

Install from PyPI:

pip install django-telegram-auth

Install locally from this repository:

pip install -e .

Django Configuration

Add Django REST Framework to INSTALLED_APPS. If you use TelegramBotApiAuthentication, also add DRF's token app.

INSTALLED_APPS = [
    # ...
    "rest_framework",
    "rest_framework.authtoken",
]

The configured user model must contain a field that stores the Telegram user ID. By default, this package uses telegram_user_id.

from django.contrib.auth.models import AbstractUser
from django.db import models


class User(AbstractUser):
    telegram_user_id = models.BigIntegerField(unique=True, null=True, blank=True)

Telegram Web App Authentication

Use TelegramWebAppAuthentication when clients authenticate with Telegram Web App initData.

Settings

TELEGRAM_WEBAPP_AUTH_BOT_TOKEN = "123456:your-telegram-bot-token"
TELEGRAM_WEBAPP_AUTH_MODEL = "accounts.User"

# Optional. Defaults to "telegram_user_id".
TELEGRAM_WEBAPP_AUTH_PK_FIELD_NAME = "telegram_user_id"

# Optional. Defaults to 300 seconds.
# Set to None to disable replay-age validation.
TELEGRAM_WEBAPP_AUTH_MAX_AGE_SECONDS = 300

# Optional. Defaults to 0 seconds.
# Added to server time before validating auth_date.
TELEGRAM_WEBAPP_AUTH_TIME_DELTA_SECONDS = 0

Use Globally

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "django_telegram_auth.authentication.TelegramWebAppAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        "django_telegram_auth.permissions.TelegramWebAppPermission",
    ],
}

Use On A View

from rest_framework.views import APIView
from django_telegram_auth.authentication import TelegramWebAppAuthentication
from django_telegram_auth.permissions import TelegramWebAppPermission


class ProfileView(APIView):
    authentication_classes = [TelegramWebAppAuthentication]
    permission_classes = [TelegramWebAppPermission]

    def get(self, request):
        ...

Request Header

Send the Telegram Web App initData value as a base64-encoded authorization token.

Authorization: TgWebApp <base64-encoded-init-data>

JavaScript example:

const initData = window.Telegram.WebApp.initData;
const encodedInitData = btoa(initData);

fetch("/api/profile/", {
  headers: {
    Authorization: `TgWebApp ${encodedInitData}`,
  },
});

When authentication succeeds:

  • request.user is the Django model instance matched by Telegram user ID.
  • request.auth is a WebAppUser instance parsed from Telegram user data.

Telegram Bot API Authentication

Use TelegramBotApiAuthentication when a trusted bot or backend service calls your API on behalf of a Telegram user.

This authentication method requires a valid DRF token owned by a Django superuser. The request token format is:

<drf-token>_<telegram-user-id>

Settings

TELEGRAM_BOT_API_AUTH_MODEL = "accounts.User"

# Optional. Defaults to "telegram_user_id".
TELEGRAM_BOT_API_AUTH_PK_FIELD_NAME = "telegram_user_id"

Use Globally

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "django_telegram_auth.authentication.TelegramBotApiAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        "django_telegram_auth.permissions.TelegramBotApiPermission",
    ],
}

Use On A View

from rest_framework.views import APIView
from django_telegram_auth.authentication import TelegramBotApiAuthentication
from django_telegram_auth.permissions import TelegramBotApiPermission


class BotProxyView(APIView):
    authentication_classes = [TelegramBotApiAuthentication]
    permission_classes = [TelegramBotApiPermission]

    def post(self, request):
        ...

Request Header

Authorization: TgBotApi <drf-token>_<telegram-user-id>

Example:

Authorization: TgBotApi 0123456789abcdef_123456789

When authentication succeeds:

  • request.user is the Django model instance matched by Telegram user ID.
  • request.auth is the DRF Token instance used by the bot service.

Web App Service

TelegramWebAppService validates Telegram Web App signed data and returns a WebAppUser dataclass.

from django_telegram_auth.services import TelegramWebAppService


webapp_user = TelegramWebAppService().parse(
    token=init_data,
    bot_token="123456:your-telegram-bot-token",
    max_age=300,
    time_delta=0,
)

if webapp_user is None:
    # Invalid Telegram hash.
    ...

WebAppUser contains Telegram user fields. Only id and first_name are required; optional fields default to None.

WebAppUser(
    id: int,
    first_name: str,
    last_name: Optional[str] = None,
    username: Optional[str] = None,
    language_code: Optional[str] = None,
    is_premium: Optional[bool] = None,
    added_to_attachment_menu: Optional[bool] = None,
    allows_write_to_pm: Optional[bool] = None,
    photo_url: Optional[str] = None,
)

Authentication Flow

Web App

  1. Telegram provides signed initData to the Web App frontend.
  2. The frontend base64-encodes initData.
  3. The API receives the value in the TgWebApp authorization header.
  4. The package validates the Telegram hash with TELEGRAM_WEBAPP_AUTH_BOT_TOKEN.
  5. The package adjusts server time with TELEGRAM_WEBAPP_AUTH_TIME_DELTA_SECONDS, then rejects stale or future auth_date values.
  6. The package parses Telegram user data and looks up the configured Django model by Telegram user ID.

Bot API

  1. A trusted bot service sends TgBotApi <drf-token>_<telegram-user-id>.
  2. The package verifies that the DRF token exists and belongs to a superuser.
  3. The package looks up the configured Django model by Telegram user ID.

Custom User Lookup

Both authentication classes can be subclassed when your lookup needs more than a single telegram_user_id field.

from django_telegram_auth.authentication import TelegramWebAppAuthentication


class CustomTelegramWebAppAuthentication(TelegramWebAppAuthentication):
    def get_filters(self, request, webappuser):
        return {
            "profile__telegram_id": webappuser.id,
            "is_active": True,
        }

Then use the custom class in DRF:

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "path.to.CustomTelegramWebAppAuthentication",
    ],
}

Public Imports

from django_telegram_auth.authentication import (
    TelegramBotApiAuthentication,
    TelegramWebAppAuthentication,
)
from django_telegram_auth.permissions import (
    TelegramBotApiPermission,
    TelegramWebAppPermission,
)
from django_telegram_auth.services import TelegramWebAppService, WebAppUser

Errors

The authentication classes raise DRF AuthenticationFailed when credentials are missing, malformed, invalid, or when a matching user is not found.

Missing required settings are reported through DRF's import_from_string configuration errors or normal exceptions during authentication.

Development

Create a virtual environment and install the package in editable mode:

python -m venv .venv
source .venv/bin/activate
pip install -e .

Run the test suite with:

python3 -m unittest discover -s tests

For future changes, add focused tests for authentication class header parsing, user model lookup, and permission class behavior.

Project Metadata

License

This project is licensed under the Apache License 2.0. See LICENSE.

Metadata

Release files for django-telegram-auth 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-telegram-auth 0.0.1
File Size Uploaded Provenance
django_telegram_auth-0.0.1.tar.gz 17.9 kB Without provenance Details

Release files / django_telegram_auth-0.0.1.tar.gz

Download URL django_telegram_auth-0.0.1.tar.gz
Size 17.9 kB
Tags Source
SHA-256 checksum
How to use checksums
7a3ca88979e0ab1a40fe010d77437168d894512cb1ff3ef5f382125e8d0094c4
BLAKE2b-256 checksum
How to use checksums
435e7aea1ca12fa7642f73b8b4f9834eeba820c95bc85e7f4814443d64408d33
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.11.12

Security for django-telegram-auth 0.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Release history Release notifications | RSS feed

This release

0.0.1 This release

1 release file No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page