90 lines
3.3 KiB
C#
90 lines
3.3 KiB
C#
using Fantasy.Async;
|
|
using Fantasy.Event;
|
|
using Fantasy.Network.HTTP;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using Fantasy;
|
|
|
|
namespace NBF;
|
|
|
|
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.Converters.Add(new JsonStringEnumConverter());
|
|
});
|
|
|
|
// 2. 添加全局过滤器
|
|
self.MvcBuilder.AddMvcOptions(options =>
|
|
{
|
|
// options.Filters.Add<GameExceptionFilter>();
|
|
// options.Filters.Add<ModelValidationFilter>();
|
|
});
|
|
|
|
// 3. 配置 JWT 认证
|
|
var jwtSecret = "YourSuperSecretKeyForJwtTokenGeneration123!";
|
|
self.Builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
|
.AddJwtBearer(options =>
|
|
{
|
|
options.TokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
ValidateIssuer = true,
|
|
ValidateAudience = true,
|
|
ValidateLifetime = true,
|
|
ValidateIssuerSigningKey = true,
|
|
ValidIssuer = "GameServer",
|
|
ValidAudience = "GameClient",
|
|
IssuerSigningKey = new SymmetricSecurityKey(
|
|
Encoding.UTF8.GetBytes(jwtSecret)),
|
|
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"));
|
|
});
|
|
|
|
// 5. 配置 CORS
|
|
self.Builder.Services.AddCors(options =>
|
|
{
|
|
options.AddPolicy("GameClient", builder =>
|
|
{
|
|
builder.WithOrigins(
|
|
"https://game.example.com",
|
|
"https://cdn.game.example.com"
|
|
)
|
|
.AllowAnyMethod()
|
|
.AllowAnyHeader()
|
|
.AllowCredentials();
|
|
});
|
|
});
|
|
|
|
// // 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}");
|
|
|
|
await FTask.CompletedTask;
|
|
}
|
|
} |