TmaAuthentication.AspNetCore 1.0.1

dotnet add package TmaAuthentication.AspNetCore --version 1.0.1
                    
NuGet\Install-Package TmaAuthentication.AspNetCore -Version 1.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="TmaAuthentication.AspNetCore" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="TmaAuthentication.AspNetCore" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="TmaAuthentication.AspNetCore" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add TmaAuthentication.AspNetCore --version 1.0.1
                    
#r "nuget: TmaAuthentication.AspNetCore, 1.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package TmaAuthentication.AspNetCore@1.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=TmaAuthentication.AspNetCore&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=TmaAuthentication.AspNetCore&version=1.0.1
                    
Install as a Cake Tool

TmaAuthentication

NuGet GitHub

A C# library for validating Telegram Mini App initialization data.

Overview

TmaAuthentication is a C# library for working with Telegram Mini App initialization data. It provides functionality to:

  • Parse initialization data from a query string format
  • Validate the initialization data using the bot token
  • Sign initialization data for testing or other purposes
  • ASP.NET Core authentication infrastructure with JWT support

Installation

Add the NuGet package to your project:

# Core library
dotnet add package TmaAuthentication

# ASP.NET Core integration
dotnet add package TmaAuthentication.AspNetCore

Usage

Validating Initialization Data

The validator helps you verify if the initialization data received from Telegram is authentic and hasn't been tampered with.

// Create validator instance
var validator = new TmaInitDataValidator();

// Validate initialization data with 24-hour expiration
var initData = "query_id=AAHdF6IQAAAAAN0XohDhrOrc&user=%7B%22id%22%3A279058397%2C%22first_name%22%3A%22John%22%2C%22last_name%22%3A%22Doe%22%7D&auth_date=1713542400&hash=abc123...";
var isValid = validator.Validate(initData, "YOUR_BOT_TOKEN", TimeSpan.FromHours(24));

if (isValid)
{
    Console.WriteLine("Initialization data is valid");
}
else
{
    Console.WriteLine("Initialization data is invalid");
}

Creating Signatures

The signer helps you create valid signatures for testing or when you need to generate initialization data programmatically.

// Create signer instance
var signer = new TmaInitDataSigner();

// Create a signature from parameters
var parameters = new Dictionary<string, string>
{
    { "user", "{\"id\":123456789,\"first_name\":\"John\",\"last_name\":\"Doe\"}" },
    { "query_id", "AAHdF6IQAAAAAN0XohDhrOrc" },
    { "auth_date", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() }
};
var hash = signer.Sign(parameters, "YOUR_BOT_TOKEN");

ASP.NET Core Integration

The TmaAuthentication.AspNetCore package provides seamless integration with ASP.NET Core authentication system, supporting both direct init data validation and JWT-based authentication.

Direct Init Data Authentication

Configure direct init data authentication in your ASP.NET Core application:

builder.Services.AddTmaAuthentication(options =>
{
    options.BotToken = "YOUR_BOT_TOKEN";
    options.ExpirationInterval = TimeSpan.FromDays(7);
});

// Use the authentication
app.UseAuthentication();
app.UseAuthorization();

Clients send requests with the TAuth scheme:

Authorization: TAuth query_id=AAHdF6IQAAAAAN0XohDhrOrc&user=%7B%22id%22%3A279058397...

JWT-Based Authentication

Configure JWT authentication for better scalability:

builder.Services.AddTmaJwtAuthentication(options =>
{
    options.BotToken = "YOUR_BOT_TOKEN";
    options.InitDataExpirationInterval = TimeSpan.FromDays(7);
    options.SecretKey = "YOUR_JWT_SECRET_KEY";
    options.TokenExpiration = TimeSpan.FromHours(24);
    options.EnableBuiltInEndpoint = true; // Optional built-in token endpoint
});

The JWT workflow involves two steps:

  1. Token Generation: POST /auth/tma-token with init data to get JWT
  2. Authentication: Use standard Bearer token authentication
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Accessing Current User

Use IUserAccessor to access current user information in controllers or services:

[ApiController]
public class UserController : ControllerBase
{
    private readonly IUserAccessor _userAccessor;
    
    public UserController(IUserAccessor userAccessor)
    {
        _userAccessor = userAccessor;
    }
    
    [HttpGet("profile")]
    public IActionResult GetProfile()
    {
        if (!_userAccessor.IsAuthenticated)
            return Unauthorized();
            
        return Ok(new {
            UserId = _userAccessor.UserId,
            Name = _userAccessor.FirstName,
            Username = _userAccessor.Username,
            IsPremium = _userAccessor.IsPremium,
            AuthScheme = _userAccessor.AuthenticationScheme
        });
    }
}

Custom JWT Token Generation

You can also use ITmaJwtService for custom token generation:

[ApiController]
public class AuthController : ControllerBase
{
    private readonly ITmaJwtService _jwtService;
    
    [HttpPost("custom-token")]
    public async Task<IActionResult> GenerateToken([FromBody] string initData)
    {
        try
        {
            var token = await _jwtService.GenerateTokenAsync(initData);
            return Ok(new { token });
        }
        catch (UnauthorizedAccessException)
        {
            return Unauthorized("Invalid init data");
        }
    }
}

License

This library is open source and available under the MIT license.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.1 248 6/9/2025