身份验证

This commit is contained in:
Bob.Song
2026-04-01 16:40:34 +08:00
parent d5dafd2bcf
commit b628f0d04a
17 changed files with 590 additions and 101 deletions

View File

@@ -0,0 +1,17 @@
namespace NBF;
public enum ErrorCode
{
/// <summary>
/// 成功
/// </summary>
Success = 0,
ArgsError = 1,
Busy = 2,
/// <summary>
/// 安装包不存在
/// </summary>
AppNotFound = 404
}

View File

@@ -0,0 +1,6 @@
namespace NBF;
public class RequestArgs
{
}

View File

@@ -0,0 +1,88 @@
using Microsoft.AspNetCore.Mvc;
namespace NBF;
public abstract class NBControllerBase : ControllerBase
{
protected static readonly string BaseRootPath = $"{AppContext.BaseDirectory}wwwroot/";
public IActionResult Html(string fileName)
{
var filePath = Path.Combine(BaseRootPath, $"{fileName}.html");
if (System.IO.File.Exists(filePath))
{
return PhysicalFile(filePath, "text/html");
}
return Content($"{fileName}.html not found");
}
public OkObjectResult Error(ErrorCode code, string msg = "")
{
var res = new ResponseData<string>
{
Code = (int)code,
Data = msg
};
return Ok(res);
}
public OkObjectResult Success()
{
var res = new ResponseData<string>
{
Code = 0,
Data = string.Empty
};
return Ok(res);
}
public OkObjectResult Success<T>(T data)
{
var res = new ResponseData<T>
{
Code = 0,
Data = data
};
return Ok(res);
}
#region
/// <summary>
/// 获得请求url参数
/// </summary>
/// <returns></returns>
protected Dictionary<string, string> GetQuery()
{
Dictionary<string, string> paramMap = new Dictionary<string, string>();
var request = HttpContext.Request;
foreach (var keyValuePair in request.Query)
paramMap.Add(keyValuePair.Key, keyValuePair.Value[0]);
return paramMap;
}
protected Dictionary<string, string> GetHeaders()
{
Dictionary<string, string> paramMap = new Dictionary<string, string>();
var request = HttpContext.Request;
foreach (var keyValuePair in request.Headers)
paramMap.Add(keyValuePair.Key, keyValuePair.Value[0]);
return paramMap;
}
protected static void TryCreateDir(string path)
{
if (string.IsNullOrEmpty(path)) return;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
#endregion
}

View File

@@ -0,0 +1,9 @@
using System.Text.Json.Serialization;
namespace NBF;
public class ResponseData<T>
{
[JsonPropertyName("code")] public int Code { get; set; }
[JsonPropertyName("data")] public T Data { get; set; }
}

View File

@@ -1,40 +1,139 @@
using System.Threading;
using System.Collections.Concurrent;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using Fantasy;
using Fantasy.Async;
using Fantasy.Network.HTTP;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
namespace NBF;
[ApiController]
[Route("api/[controller]")]
[ServiceFilter(typeof(SceneContextFilter))]
public class AuthController : ControllerBase
public class AuthController : NBControllerBase
{
private static readonly ConcurrentDictionary<string, CaptchaInfo> CaptchaCache = new();
private static readonly TimeSpan CaptchaLifetime = TimeSpan.FromMinutes(10);
private readonly Scene _scene;
/// <summary>
/// 构造函数依赖注入
/// </summary>
/// <param name="scene"></param>
public AuthController(Scene scene)
{
_scene = scene;
}
[HttpGet("login")]
public async FTask<IActionResult> Login()
[AllowAnonymous]
public async FTask<IActionResult> Login([FromQuery] string account, [FromQuery] string code)
{
await DingTalkHelper.SendCAPTCHA("123456");
if (string.IsNullOrWhiteSpace(account) || string.IsNullOrWhiteSpace(code))
{
await FTask.CompletedTask;
return Error(ErrorCode.ArgsError, "account or code is empty");
}
var key = account.Trim();
if (!CaptchaCache.TryGetValue(key, out var captchaInfo))
{
await FTask.CompletedTask;
return Error(ErrorCode.ArgsError, "captcha not found");
}
if (captchaInfo.ExpireAtUtc <= DateTime.UtcNow)
{
CaptchaCache.TryRemove(key, out _);
await FTask.CompletedTask;
return Error(ErrorCode.ArgsError, "captcha expired");
}
if (!string.Equals(captchaInfo.Code, code.Trim(), StringComparison.Ordinal))
{
await FTask.CompletedTask;
return Error(ErrorCode.ArgsError, "captcha invalid");
}
CaptchaCache.TryRemove(key, out _);
var (token, expireAtUtc) = GenerateJwtToken(key);
await FTask.CompletedTask;
return Ok($"Hello from the Fantasy controller! _scene.SceneType:{_scene.SceneType} _scene.SceneType:{_scene.SceneConfigId}");
return Success(new
{
token,
expireAtUtc
});
}
[HttpGet("code")]
public async FTask<IActionResult> SendCode()
[AllowAnonymous]
public async FTask<IActionResult> SendCode([FromQuery] string account)
{
await DingTalkHelper.SendCAPTCHA("123456");
await FTask.CompletedTask;
return Ok($"Hello from the Fantasy controller! _scene.SceneType:{_scene.SceneType} _scene.SceneType:{_scene.SceneConfigId}");
if (string.IsNullOrWhiteSpace(account))
{
await FTask.CompletedTask;
return Error(ErrorCode.ArgsError, "account is empty");
}
var key = account.Trim();
var captchaCode = RandomNumberGenerator.GetInt32(0, 1_000_000).ToString("D6");
var expireAtUtc = DateTime.UtcNow.Add(CaptchaLifetime);
CaptchaCache[key] = new CaptchaInfo
{
Code = captchaCode,
ExpireAtUtc = expireAtUtc
};
await DingTalkHelper.SendCAPTCHA(account, captchaCode);
return Success();
}
[HttpGet("me")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public IActionResult Me()
{
var account = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? string.Empty;
return Success(new
{
account
});
}
private static (string Token, DateTime ExpireAtUtc) GenerateJwtToken(string account)
{
var now = DateTime.UtcNow;
var expireAtUtc = now.Add(ApiJwtHelper.TokenLifetime);
var tokenHandler = new JwtSecurityTokenHandler();
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, account),
new Claim(ClaimTypes.Name, account),
new Claim(ClaimTypes.Role, "Player")
};
var token = tokenHandler.CreateToken(new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = expireAtUtc,
NotBefore = now,
Issuer = ApiJwtHelper.Issuer,
Audience = ApiJwtHelper.Audience,
SigningCredentials = new SigningCredentials(
ApiJwtHelper.CreateSigningKey(),
SecurityAlgorithms.HmacSha256)
});
return (tokenHandler.WriteToken(token), expireAtUtc);
}
private sealed class CaptchaInfo
{
public string Code { get; init; } = string.Empty;
public DateTime ExpireAtUtc { get; init; }
}
}

View File

@@ -0,0 +1,33 @@
using System.Threading;
using Fantasy;
using Fantasy.Async;
using Fantasy.Network.HTTP;
using Microsoft.AspNetCore.Mvc;
namespace NBF;
/// <summary>
/// 用户api
/// </summary>
[ApiController]
[Route("api/[controller]")]
[ServiceFilter(typeof(SceneContextFilter))]
public class UserController : NBControllerBase
{
private readonly Scene _scene;
/// <summary>
/// 构造函数依赖注入
/// </summary>
/// <param name="scene"></param>
public UserController(Scene scene)
{
_scene = scene;
}
[HttpGet("test")]
public async FTask<IActionResult> SendCode()
{
return Success("test");
}
}

View File

@@ -1,66 +1,60 @@
using System;
using Fantasy;
using Fantasy.Async;
using Fantasy.Event;
using Fantasy.Network.HTTP;
using Microsoft.AspNetCore.Builder;
using System;
using Fantasy;
namespace NBF
namespace NBF;
public class GameHttpApplicationHandler : AsyncEventSystem<OnConfigureHttpApplication>
{
public class GameHttpApplicationHandler : AsyncEventSystem<OnConfigureHttpApplication>
protected override async FTask Handler(OnConfigureHttpApplication self)
{
protected override async FTask Handler(OnConfigureHttpApplication self)
var app = self.Application;
app.UseCors("GameClient");
app.Use(async (context, next) =>
{
var app = self.Application;
var requestId = Guid.NewGuid().ToString("N");
context.Items["RequestId"] = requestId;
// 1. CORS必须在认证之前
app.UseCors("GameClient");
var start = DateTime.UtcNow;
var method = context.Request.Method;
var path = context.Request.Path;
var ip = context.Connection.RemoteIpAddress?.ToString();
// 2. 请求日志中间件
app.Use(async (context, next) =>
Log.Info($"[HTTP-{requestId}] {method} {path} - IP: {ip}");
try
{
var requestId = Guid.NewGuid().ToString("N");
context.Items["RequestId"] = requestId;
var start = DateTime.UtcNow;
var method = context.Request.Method;
var path = context.Request.Path;
var ip = context.Connection.RemoteIpAddress?.ToString();
Log.Info($"[HTTP-{requestId}] {method} {path} - IP: {ip}");
try
{
await next.Invoke();
var duration = (DateTime.UtcNow - start).TotalMilliseconds;
var status = context.Response.StatusCode;
Log.Info($"[HTTP-{requestId}] {status} - {duration}ms");
}
catch (Exception e)
{
Log.Error($"[HTTP-{requestId}] 异常: {e.Message}");
throw;
}
});
// 3. 认证
app.UseAuthentication();
// 4. 授权
app.UseAuthorization();
// 5. 自定义响应头
app.Use(async (context, next) =>
{
context.Response.Headers.Add("X-Game-Server", "NBF");
context.Response.Headers.Add("X-Server-Version", "1.0.0");
await next.Invoke();
});
Log.Info($"[HTTP] 游戏应用配置完成: Scene {self.Scene.SceneConfigId}");
var duration = (DateTime.UtcNow - start).TotalMilliseconds;
var status = context.Response.StatusCode;
Log.Info($"[HTTP-{requestId}] {status} - {duration}ms");
}
catch (Exception e)
{
Log.Error($"[HTTP-{requestId}] exception: {e.Message}");
throw;
}
});
await FTask.CompletedTask;
}
app.UseAuthentication();
app.UseApiJwtGuard();
app.UseAuthorization();
app.Use(async (context, next) =>
{
context.Response.Headers["X-Game-Server"] = "NBF";
context.Response.Headers["X-Server-Version"] = "1.0.0";
await next.Invoke();
});
Log.Info($"[HTTP] game application configured: Scene {self.Scene.SceneConfigId}");
await FTask.CompletedTask;
}
}
}

View File

@@ -1,13 +1,14 @@
using Fantasy;
using Fantasy.Async;
using Fantasy.Event;
using Fantasy.Network.HTTP;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using Fantasy;
namespace NBF;
@@ -15,25 +16,39 @@ public class GameHttpServicesHandler : AsyncEventSystem<OnConfigureHttpServices>
{
protected override async FTask Handler(OnConfigureHttpServices self)
{
// 1. 配置 JSON 序列化
self.MvcBuilder.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.WriteIndented = true;
options.JsonSerializerOptions.DefaultIgnoreCondition =
JsonIgnoreCondition.WhenWritingNull;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
// 2. 添加全局过滤器
self.MvcBuilder.AddMvcOptions(options =>
{
// options.Filters.Add<GameExceptionFilter>();
// options.Filters.Add<ModelValidationFilter>();
});
// 3. 配置 JWT 认证
var jwtSecret = "YourSuperSecretKeyForJwtTokenGeneration123!";
self.MvcBuilder.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var errorText = string.Join("; ", context.ModelState
.Where(kv => kv.Value is { Errors.Count: > 0 })
.Select(kv => $"{kv.Key}: {string.Join(", ", kv.Value!.Errors.Select(e => e.ErrorMessage))}"));
var response = new ResponseData<string>
{
Code = (int)ErrorCode.ArgsError,
Data = string.IsNullOrWhiteSpace(errorText) ? "args error" : errorText
};
// Keep API error style consistent with NBControllerBase.Error(): HTTP 200 + business code.
return new OkObjectResult(response);
};
});
self.Builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
@@ -43,26 +58,20 @@ public class GameHttpServicesHandler : AsyncEventSystem<OnConfigureHttpServices>
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "GameServer",
ValidAudience = "GameClient",
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(jwtSecret)),
ValidIssuer = ApiJwtHelper.Issuer,
ValidAudience = ApiJwtHelper.Audience,
IssuerSigningKey = ApiJwtHelper.CreateSigningKey(),
ClockSkew = TimeSpan.Zero
};
});
// 4. 配置授权策略
self.Builder.Services.AddAuthorization(options =>
{
options.AddPolicy("Player", policy =>
policy.RequireRole("Player", "Admin"));
options.AddPolicy("Admin", policy =>
policy.RequireRole("Admin"));
options.AddPolicy("VIP", policy =>
policy.RequireClaim("VIPLevel"));
options.AddPolicy("Player", policy => policy.RequireRole("Player", "Admin"));
options.AddPolicy("Admin", policy => policy.RequireRole("Admin"));
options.AddPolicy("VIP", policy => policy.RequireClaim("VIPLevel"));
});
// 5. 配置 CORS
self.Builder.Services.AddCors(options =>
{
options.AddPolicy("GameClient", builder =>
@@ -77,14 +86,7 @@ public class GameHttpServicesHandler : AsyncEventSystem<OnConfigureHttpServices>
});
});
// // 6. 注册游戏服务
// self.Builder.Services.AddSingleton<IPlayerService, PlayerService>();
// self.Builder.Services.AddSingleton<IGuildService, GuildService>();
// self.Builder.Services.AddScoped<IAuthService, AuthService>();
// self.Builder.Services.AddScoped<IGameRepository, GameRepository>();
Log.Info($"[HTTP] 游戏服务配置完成: Scene {self.Scene.SceneConfigId}");
Log.Info($"[HTTP] game service configured: Scene {self.Scene.SceneConfigId}");
await FTask.CompletedTask;
}
}
}

View File

@@ -0,0 +1,17 @@
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace NBF;
public static class ApiJwtHelper
{
public const string Issuer = "GameServer";
public const string Audience = "GameClient";
public const string Secret = "YourSuperSecretKeyForJwtTokenGeneration123!";
public static readonly TimeSpan TokenLifetime = TimeSpan.FromDays(1);
public static SymmetricSecurityKey CreateSigningKey()
{
return new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Secret));
}
}

View File

@@ -8,14 +8,14 @@ public static class DingTalkHelper
{
private static readonly HttpClient _httpClient = new HttpClient();
public static async Task SendCAPTCHA(string code)
public static async Task SendCAPTCHA(string account, string code)
{
DingTalkMarkdownData dingTalkTestData = new DingTalkMarkdownData
{
markdown = new DingTalkMarkdownItem
{
title = "NB验证码",
text = $"验证码:{code}"
text = $"账号:{account}\n验证码:{code}"
}
};
await SendMessageAsync("23457f9c93ac0ae909e1cbf8bcfeb7e0573968ac2d4c4b2c3a961b2f0c9247cb", dingTalkTestData);

View File

@@ -0,0 +1,63 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
namespace NBF;
public sealed class ApiJwtGuardMiddleware
{
private readonly RequestDelegate _next;
public ApiJwtGuardMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (HttpMethods.IsOptions(context.Request.Method))
{
await _next(context);
return;
}
var path = context.Request.Path.Value ?? string.Empty;
var normalizedPath = path.Length > 1 ? path.TrimEnd('/') : path;
if (!normalizedPath.StartsWith("/api/", StringComparison.OrdinalIgnoreCase))
{
await _next(context);
return;
}
// Endpoint carries AllowAnonymous metadata when action/controller has [AllowAnonymous].
var endpoint = context.GetEndpoint();
if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null)
{
await _next(context);
return;
}
if (context.User?.Identity?.IsAuthenticated != true)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsJsonAsync(new ResponseData<string>
{
Code = StatusCodes.Status401Unauthorized,
Data = "unauthorized"
});
return;
}
await _next(context);
}
}
public static class ApiJwtGuardMiddlewareExtensions
{
public static IApplicationBuilder UseApiJwtGuard(this IApplicationBuilder app)
{
return app.UseMiddleware<ApiJwtGuardMiddleware>();
}
}

View File

@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<RootNamespace>Hotfix</RootNamespace>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<ItemGroup>