身份验证

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

@@ -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;
}
}
}