Files
StoreWeb/Tests/Store.Users.Tests/DevelopmentTokenTests.cs
T
2026-10-23 19:28:17 +08:00

49 lines
2.1 KiB
C#

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<string, string?>
{
["Jwt:DevelopmentToken:Enabled"] = enabled.ToString(),
["Jwt:DevelopmentToken:Token"] = "test-fixed-token",
["Jwt:DevelopmentToken:UserName"] = "admin"
});
using var db = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, "Data Source=:memory:").Build();
db.CodeFirst.SyncStructure<OnlineUserInfo>();
builder.Services.AddSingleton<IFreeSql>(db);
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"));
}
}