đˇ C# Code Examples
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Net.NetworkInformation;
using System.Linq;
using System.Management;
namespace TKIAuth
{
public class AuthRequest
{
public AuthData data { get; set; }
}
public class AuthData
{
public string product { get; set; }
public string version { get; set; }
public string licensekey { get; set; }
public string ip { get; set; }
public string hwid { get; set; }
}
public class AuthResponse
{
public string status_overview { get; set; }
public string status_msg { get; set; }
public string discord_username { get; set; }
public string discord_tag { get; set; }
public string discord_id { get; set; }
public string expire_date { get; set; }
public bool staff_license { get; set; }
public string version { get; set; }
public string message { get; set; }
}
public class TKIAuthClient
{
private const string API_KEY = "your-api-key-here";
private const string API_URL = "http://your-domain.com/api/license/auth";
private const string PRODUCT = "MyCSharpApp";
private const string VERSION = "1.0.0";
private readonly HttpClient _httpClient;
private readonly JsonSerializerOptions _jsonOptions;
public TKIAuthClient()
{
_httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(30)
};
_httpClient.DefaultRequestHeaders.Add("Authorization", API_KEY);
_httpClient.DefaultRequestHeaders.Add("User-Agent", "TKI-Auth-CSharp/1.0");
_jsonOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
};
}
private string GetHWID()
{
try
{
// Get MAC address
var mac = NetworkInterface.GetAllNetworkInterfaces()
.Where(nic => nic.OperationalStatus == OperationalStatus.Up &&
nic.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.Select(nic => nic.GetPhysicalAddress().ToString())
.FirstOrDefault();
// Get processor ID
var processorId = "";
try
{
using (var searcher = new ManagementObjectSearcher("SELECT ProcessorId FROM Win32_Processor"))
{
foreach (ManagementObject obj in searcher.Get())
{
processorId = obj["ProcessorId"]?.ToString();
break;
}
}
}
catch { }
var hwString = $"{Environment.MachineName}-{mac}-{processorId}";
using (var md5 = MD5.Create())
{
var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(hwString));
var hashString = Convert.ToHexString(hash);
return $"CS-{hashString[..16]}";
}
}
catch
{
return $"CS-FALLBACK-{DateTime.Now.Ticks % 1000000}";
}
}
private string GetLocalIP()
{
try
{
using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(5) })
{
var response = client.GetStringAsync("https://api.ipify.org").Result;
return response.Trim();
}
}
catch
{
return "127.0.0.1";
}
}
public async Task<(bool Success, AuthResponse Response, string Error)> AuthenticateAsync(
string licenseKey, string ip = null, string hwid = null)
{
try
{
var request = new AuthRequest
{
data = new AuthData
{
product = PRODUCT,
version = VERSION,
licensekey = licenseKey,
ip = ip ?? GetLocalIP(),
hwid = hwid ?? GetHWID()
}
};
var json = JsonSerializer.Serialize(request, _jsonOptions);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(API_URL, content);
var responseBody = await response.Content.ReadAsStringAsync();
var authResponse = JsonSerializer.Deserialize<AuthResponse>(responseBody, _jsonOptions);
if (response.IsSuccessStatusCode && authResponse.status_overview == "success")
{
return (true, authResponse, null);
}
else
{
var error = authResponse.message ?? $"HTTP {(int)response.StatusCode}";
return (false, authResponse, error);
}
}
catch (Exception ex)
{
return (false, null, $"Network error: {ex.Message}");
}
}
public async Task<(bool Success, AuthResponse Response, string Error)> AuthenticateWithRetryAsync(
string licenseKey, int maxRetries = 3, string ip = null, string hwid = null)
{
string lastError = "";
for (int attempt = 1; attempt <= maxRetries; attempt++)
{
var (success, response, error) = await AuthenticateAsync(licenseKey, ip, hwid);
if (success)
{
return (true, response, null);
}
lastError = error;
if (attempt < maxRetries)
{
var waitTime = attempt * 2000; // 2, 4, 6 seconds
Console.WriteLine($"Attempt {attempt} failed, retrying in {waitTime}ms...");
await Task.Delay(waitTime);
}
}
return (false, null, lastError);
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
public class LicenseManager : IDisposable
{
private readonly TKIAuthClient _authClient;
private AuthResponse _licenseInfo;
private bool _isAuthenticated;
private Timer _validationTimer;
private string _licenseKey;
public bool IsAuthenticated => _isAuthenticated;
public AuthResponse LicenseInfo => _licenseInfo;
public LicenseManager()
{
_authClient = new TKIAuthClient();
}
public async Task<bool> AuthenticateAsync(string licenseKey)
{
Console.WriteLine("Authenticating license...");
var (success, response, error) = await _authClient.AuthenticateWithRetryAsync(licenseKey);
if (success)
{
_isAuthenticated = true;
_licenseInfo = response;
_licenseKey = licenseKey;
Console.WriteLine("â License authenticated!");
Console.WriteLine($" User: {response.discord_username}");
Console.WriteLine($" Tag: {response.discord_tag}");
Console.WriteLine($" Expires: {response.expire_date}");
Console.WriteLine($" Staff License: {response.staff_license}");
return true;
}
else
{
Console.WriteLine($"â Authentication failed: {error}");
return false;
}
}
public void StartPeriodicValidation(TimeSpan interval)
{
_validationTimer = new Timer(async _ => await ValidatePeriodicAsync(),
null, interval, interval);
}
private async Task ValidatePeriodicAsync()
{
if (!_isAuthenticated || string.IsNullOrEmpty(_licenseKey))
return;
var (success, _, error) = await _authClient.AuthenticateAsync(_licenseKey);
if (success)
{
Console.WriteLine("â Periodic validation successful");
}
else
{
Console.WriteLine($"â Periodic validation failed: {error}");
OnLicenseExpired();
}
}
private void OnLicenseExpired()
{
_isAuthenticated = false;
_licenseInfo = null;
Console.WriteLine("License expired or validation failed!");
// Implement your logic here
}
public void Dispose()
{
_validationTimer?.Dispose();
_authClient?.Dispose();
}
}
// Console Application
public class Program
{
public static async Task<int> Main(string[] args)
{
using var licenseManager = new LicenseManager();
Console.Write("Enter license key: ");
var licenseKey = Console.ReadLine()?.Trim();
if (string.IsNullOrEmpty(licenseKey))
{
Console.WriteLine("No license key provided!");
return 1;
}
if (!await licenseManager.AuthenticateAsync(licenseKey))
{
return 1;
}
// Start periodic validation every 30 minutes
licenseManager.StartPeriodicValidation(TimeSpan.FromMinutes(30));
Console.WriteLine("Starting application...");
// Simulate application running
for (int i = 0; i < 10 && licenseManager.IsAuthenticated; i++)
{
Console.WriteLine($"Application is running... (iteration {i + 1})");
await Task.Delay(2000);
}
if (licenseManager.IsAuthenticated)
{
Console.WriteLine("Application completed successfully!");
return 0;
}
else
{
Console.WriteLine("Application stopped due to license issues");
return 1;
}
}
}
}
WPF Application Exampleâ
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
namespace TKIAuth.WPF
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
private readonly LicenseManager _licenseManager;
private string _statusText = "Not authenticated";
private bool _isAuthenticated;
public string StatusText
{
get => _statusText;
set
{
_statusText = value;
OnPropertyChanged();
}
}
public bool IsAuthenticated
{
get => _isAuthenticated;
set
{
_isAuthenticated = value;
OnPropertyChanged();
}
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
_licenseManager = new LicenseManager();
}
private async void AuthenticateButton_Click(object sender, RoutedEventArgs e)
{
var licenseKey = LicenseKeyTextBox.Text.Trim();
if (string.IsNullOrEmpty(licenseKey))
{
MessageBox.Show("Please enter a license key.", "Error",
MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
AuthenticateButton.IsEnabled = false;
StatusText = "Authenticating...";
try
{
if (await _licenseManager.AuthenticateAsync(licenseKey))
{
IsAuthenticated = true;
StatusText = $"Authenticated as {_licenseManager.LicenseInfo.discord_username}";
// Start periodic validation
_licenseManager.StartPeriodicValidation(TimeSpan.FromMinutes(30));
// Enable application features
EnableApplicationFeatures();
}
else
{
StatusText = "Authentication failed";
MessageBox.Show("License authentication failed!", "Error",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
finally
{
AuthenticateButton.IsEnabled = true;
}
}
private void EnableApplicationFeatures()
{
// Enable your application's main functionality here
AppContentPanel.Visibility = Visibility.Visible;
LoginPanel.Visibility = Visibility.Collapsed;
}
protected override void OnClosed(EventArgs e)
{
_licenseManager?.Dispose();
base.OnClosed(e);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
ASP.NET Core Web API Exampleâ
using Microsoft.AspNetCore.Mvc;
namespace TKIAuth.WebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly LicenseManager _licenseManager;
public AuthController(LicenseManager licenseManager)
{
_licenseManager = licenseManager;
}
[HttpPost("validate")]
public async Task<IActionResult> ValidateLicense([FromBody] ValidateLicenseRequest request)
{
if (string.IsNullOrEmpty(request.LicenseKey))
{
return BadRequest(new { error = "License key is required" });
}
if (await _licenseManager.AuthenticateAsync(request.LicenseKey))
{
return Ok(new
{
success = true,
user = _licenseManager.LicenseInfo.discord_username,
expires = _licenseManager.LicenseInfo.expire_date,
staff = _licenseManager.LicenseInfo.staff_license
});
}
else
{
return Unauthorized(new { error = "Invalid license key" });
}
}
[HttpGet("status")]
public IActionResult GetStatus()
{
return Ok(new
{
authenticated = _licenseManager.IsAuthenticated,
user = _licenseManager.LicenseInfo?.discord_username
});
}
}
public class ValidateLicenseRequest
{
public string LicenseKey { get; set; }
}
// Startup.cs or Program.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<LicenseManager>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Project File (.csproj)â
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Text.Json" Version="8.0.0" />
<PackageReference Include="System.Management" Version="8.0.0" />
</ItemGroup>
</Project>
Build and Runâ
# Build the project
dotnet build
# Run the application
dotnet run
# Publish for deployment
dotnet publish -c Release -r win-x64 --self-contained