/**
* SaaS授权系统 - C# / .NET 客户端
*
* 使用说明:
* 1. 修改 API_KEY 为您的真实API密钥
* 2. 在您的项目中引入此类
* 3. 调用验证:AuthorizationClient.Verify("AUTH_CODE")
*
* 依赖:.NET Standard 2.0+ / .NET Core 3.1+ / .NET 5+
* NuGet: System.Net.Http.Json (可选)
*
* @author 授权系统
* @version 1.0.0
*/
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace Kuio.Authorization
{
// ==================== 配置区 ====================
///
/// 授权客户端 - 用于验证软件授权码
///
public class AuthorizationClient
{
///
/// API密钥(从开发者中心获取)
/// 网址:https://kuio.cn/user/developer
///
public string ApiKey { get; set; } = "your_api_key_here";
///
/// API接口地址
///
public string BaseUrl { get; set; } = "https://kuio.cn/api/saas";
///
/// 是否启用缓存
///
public bool CacheEnabled { get; set; } = true;
///
/// 缓存时长(秒),默认30分钟
///
public int CacheDuration { get; set; } = 1800;
private static readonly HttpClient _httpClient = new HttpClient()
{
Timeout = TimeSpan.FromSeconds(10)
};
private readonly Dictionary _cache = new Dictionary();
// ==================== 核心方法 ====================
///
/// 验证授权(带缓存)
///
/// 授权码
public async Task VerifyAsync(string authCode)
{
return await VerifyAsync(authCode, null, null);
}
///
/// 验证授权(带域名和IP,带缓存)
///
public async Task VerifyAsync(string authCode, string domain, string ip)
{
// 1. 尝试从缓存读取
if (CacheEnabled && _cache.ContainsKey(authCode))
{
var cached = _cache[authCode];
if ((DateTime.UtcNow - cached.Timestamp).TotalSeconds < CacheDuration)
{
return new AuthResult(true, "授权验证成功(缓存)", cached.Data, true);
}
_cache.Remove(authCode);
}
// 2. 调用API验证
var result = await VerifyFromApiAsync(authCode, domain, ip);
// 3. 成功则写入缓存
if (result.Success && CacheEnabled)
{
_cache[authCode] = new CacheItem(result.Data, DateTime.UtcNow);
}
return result;
}
///
/// 从API验证授权(不使用缓存)
///
private async Task VerifyFromApiAsync(string authCode, string domain, string ip)
{
var url = $"{BaseUrl}/verify";
var requestBody = new Dictionary
{
{ "authcode", authCode }
};
if (!string.IsNullOrEmpty(domain)) requestBody["domain"] = domain;
if (!string.IsNullOrEmpty(ip)) requestBody["ip"] = ip;
var json = JsonSerializer.Serialize(requestBody);
var content = new StringContent(json, Encoding.UTF8, "application/json");
using (var request = new HttpRequestMessage(HttpMethod.Post, url))
{
request.Content = content;
request.Headers.Add("X-API-Key", ApiKey);
request.Headers.Add("User-Agent", "CSharp-AuthClient/1.0");
using (var response = await _httpClient.SendAsync(request))
{
var responseBody = await response.Content.ReadAsStringAsync();
using (JsonDocument doc = JsonDocument.Parse(responseBody))
{
var root = doc.RootElement;
var code = root.TryGetProperty("code", out var codeProp) ? codeProp.GetInt32() : -1;
var msg = root.TryGetProperty("msg", out var msgProp) ? msgProp.GetString() : "";
var data = root.TryGetProperty("data", out var dataProp) ? dataProp.GetRawText() : "{}";
if (response.StatusCode == System.Net.HttpStatusCode.OK && code == 0)
{
return new AuthResult(true, msg ?? "授权验证成功", data, false);
}
return new AuthResult(false, msg ?? "授权验证失败", "", false, code, (int)response.StatusCode);
}
}
}
}
///
/// 同步验证授权(封装异步方法)
///
public AuthResult Verify(string authCode)
{
return VerifyAsync(authCode).GetAwaiter().GetResult();
}
///
/// 快速检查授权是否有效
///
public async Task CheckAsync(string authCode)
{
var result = await VerifyAsync(authCode);
return result.Success;
}
///
/// 清除缓存
///
public void ClearCache()
{
_cache.Clear();
}
}
// ==================== 数据结构 ====================
///
/// 授权验证结果
///
public class AuthResult
{
public bool Success { get; }
public string Message { get; }
public string Data { get; }
public bool FromCache { get; }
public int Code { get; }
public int HttpCode { get; }
public AuthResult(bool success, string message, string data, bool fromCache,
int code = 0, int httpCode = 200)
{
Success = success;
Message = message;
Data = data;
FromCache = fromCache;
Code = code;
HttpCode = httpCode;
}
public override string ToString()
{
return $"AuthResult{{Success={Success}, Message='{Message}', FromCache={FromCache}}}";
}
}
///
/// 缓存项
///
internal class CacheItem
{
public string Data { get; }
public DateTime Timestamp { get; }
public CacheItem(string data, DateTime timestamp)
{
Data = data;
Timestamp = timestamp;
}
}
}
/*
// ========== 使用示例 ==========
using System;
using Kuio.Authorization;
class Program
{
static async Task Main(string[] args)
{
// 创建客户端
var client = new AuthorizationClient
{
ApiKey = "your_api_key_here"
};
// 示例1:基础验证
var result = await client.VerifyAsync("ABC123XYZ");
if (result.Success)
{
Console.WriteLine("✅ 授权验证成功!");
Console.WriteLine($"消息:{result.Message}");
Console.WriteLine($"数据:{result.Data}");
}
else
{
Console.WriteLine($"❌ 授权验证失败:{result.Message}");
}
// 示例2:带域名的验证
var result2 = await client.VerifyAsync("ABC123XYZ", "example.com", null);
// 示例3:快速检查
if (await client.CheckAsync("CODE"))
{
Console.WriteLine("✅ 授权有效");
}
// 示例4:同步调用
var syncResult = client.Verify("CODE");
// 示例5:清除缓存
client.ClearCache();
}
}
*/