TgMiniAppAuth is a .NET library that simplifies Telegram Mini App authentication and authorization for ASP.NET Core applications.
- Seamless integration with ASP.NET Core
- Built-in Telegram Mini App authentication handler
- Customizable authorization policies
- Easy access to authenticated Telegram user data
- Support for .NET 7.0 and 8.0
dotnet add package TgMiniAppAuth
- Configure services in
Program.cs
:
using TgMiniAppAuth;
services.AddTgMiniAppAuth(configuration);
- Add to
appsettings.json
:
"TelegramMiniAppAuthorizationOptions": {
"Token": "YOUR_BOT_TOKEN",
"AuthDataValidInterval": "01:00:00"
}
- Use in your controller:
[Authorize(AuthenticationSchemes = TgMiniAppAuthConstants.AuthenticationScheme)]
public class TelegramController : ControllerBase
{
private readonly ITelegramUserAccessor _telegramUserAccessor;
public TelegramController(ITelegramUserAccessor telegramUserAccessor)
{
_telegramUserAccessor = telegramUserAccessor;
}
[HttpGet("user")]
public IActionResult GetUser()
{
return Ok(_telegramUserAccessor.User);
}
}
- Client-side implementation:
const tgWebApp = window.Telegram.WebApp;
async function fetchUserData() {
const response = await fetch('/api/telegram/user', {
headers: {
'Authorization': `TMiniApp ${tgWebApp.initData}`
}
});
const userData = await response.json();
console.log(userData);
}
services.AddAuthorization(options =>
{
options.AddPolicy("PremiumUsers", policy =>
{
policy.AddAuthenticationSchemes(TgMiniAppAuthConstants.AuthenticationScheme);
policy.RequireAuthenticatedUser();
policy.RequireAssertion(context =>
{
var user = context.User;
return user.HasClaim(c => c.Type == TgMiniAppAuthConstants.Claims.IsPremium && c.Value == "True");
});
});
});
Use the policy in your controllers:
[Authorize(Policy = "PremiumUsers")]
public IActionResult PremiumContent()
{
// ...
}
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.