using MAX.Framework.DependencyInjection; using MAX.Framework.Security; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Store.Users.Tests; public sealed class DevelopmentTokenTests { [Theory] [InlineData("Development", true, "test-fixed-token", "admin")] [InlineData("Development", true, "incorrect-token", "")] [InlineData("Development", false, "test-fixed-token", "")] [InlineData("Production", true, "test-fixed-token", "")] public async Task FixedToken_OnlyAuthenticatesWhenEnabledInDevelopment( string environment, bool enabled, string token, string expectedUser) { var builder = WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = environment }); builder.WebHost.UseTestServer(); builder.Logging.ClearProviders(); builder.Configuration.AddInMemoryCollection(new Dictionary { ["Jwt:DevelopmentToken:Enabled"] = enabled.ToString(), ["Jwt:DevelopmentToken:Token"] = "test-fixed-token", ["Jwt:DevelopmentToken:UserName"] = "admin" }); builder.Services.AddStoreHubJwt(builder.Configuration); await using var app = builder.Build(); app.UseAuthentication(); app.MapGet("/identity", (ICurrentUser user) => user.IsAuthenticated ? user.UserName : ""); await app.StartAsync(); using var client = app.GetTestClient(); client.DefaultRequestHeaders.Authorization = new("Bearer", token); Assert.Equal(expectedUser, await client.GetStringAsync("/identity")); // 同一凭据不依赖首次请求创建的会话。 Assert.Equal(expectedUser, await client.GetStringAsync("/identity")); } }