身份验证
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user