gpt4 book ai didi

asp.net-core - 如何使用 [Authorize] 属性集成测试 ASP 5/Core Web API

转载 作者:行者123 更新时间:2023-12-01 23:48:55 24 4
gpt4 key购买 nike

我目前有一个 ASP 5/ASP Core Web API,需要与 OWIN 测试服务器进行集成测试。

问题是我在生产中使用 IdentityServer 作为授权服务器,并且我不想将授权包含在集成测试中。

这是 API 的 Startup.cs:

public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
IConfigurationBuilder builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true);

if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}

builder.AddEnvironmentVariables();
Configuration = builder.Build().ReloadOnChanged("appsettings.json");
}

public IConfigurationRoot Configuration { get; set; }

// This method gets called by the runtime. Use this method to add services to the container
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);

ConfigureEntityFrameworkDatabase(services, Configuration);

services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<HoehenSuchtIdentityDbContext>()
.AddDefaultTokenProviders();

ConfigureMvc(services);

// register autofac as dependency resolver
ContainerBuilder containerBuilder = new ContainerBuilder();

// register all required autofac modules
RegisterAutofacModules(containerBuilder);

// register all automapper mappings as di services so there dependencies can be resolved
ConfigureAutomapper(containerBuilder);

ConfigureSwagger(services);

// copy all asp core dependency injection registrations to autofac
containerBuilder.Populate(services);
IContainer container = containerBuilder.Build();

return container.Resolve<IServiceProvider>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}

// make sure the database was created and all migrations applied
MigrateDatabase(app);
app.ApplicationServices.GetService<HoehenSuchtDbContext>().EnsureSeedData(env);

app.UseIISPlatformHandler();

app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();

ConfigureIdentityServer(app, Configuration);

app.UseStaticFiles();

app.UseMvc();

//app.UseSwaggerGen(/*routeTemplate: "docs/{apiVersion}/swagger.json"*/);
//app.UseSwaggerUi(/*baseRoute: "docs", swaggerUrl: "docs/v1/swagger.json"*/);
}

public static Action<IServiceCollection, IConfigurationRoot> ConfigureEntityFrameworkDatabase = (services, config) =>
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<HoehenSuchtDbContext>(builder =>
builder.UseSqlServer(config["Data:DefaultConnection:ConnectionString"]))
.AddDbContext<HoehenSuchtIdentityDbContext>(builder =>
builder.UseSqlServer(config["Data:IdentityConnection:ConnectionString"]));
};

public static Action<IServiceCollection> ConfigureMvc = services =>
{
services.AddMvc().AddControllersAsServices(new List<Assembly> { typeof(Startup).GetTypeInfo().Assembly });
};

我已经尝试注册一个特殊的测试中间件,理论上它应该进行身份验证并设置声明主体。但在 OWIN 管道下游的某个地方,身份验证被拒绝,我收到 401 错误代码。

这就是我设置 OWIN 测试服务器的方式:

Startup.MigrateDatabase = app =>
{
app.ApplicationServices.GetService<HoehenSuchtDbContext>().Database.EnsureCreated();
};
Startup.ConfigureEntityFrameworkDatabase = ApiTestServer.ConfigureInMemoryDatabase;
Startup.ConfigureIdentityServer = (app, config) =>
{
app.ApplicationServices.GetService<HoehenSuchtDbContext>().EnsureSeedData(new HostingEnvironment {EnvironmentName = "development" });

app.UseMiddleware<AuthenticatedTestRequestMiddleware>();
};
Server = new TestServer(TestServer.CreateBuilder().UseStartup<Startup>());

这是我的自定义AuthenticatedTestRequestMiddleware:

public class AuthenticatedTestRequestMiddleware
{
public const string TestingCookieAuthentication = "TestCookieAuthentication";
public const string TestingHeader = "X-Integration-Testing";
public const string TestingHeaderValue = "78EAAA45-E68B-43C7-9D12-3A5F1E646BD5";

private readonly RequestDelegate _next;

public AuthenticatedTestRequestMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext context)
{
if (context.Request.Headers.Keys.Contains(TestingHeader) && context.Request.Headers[TestingHeader].First().Equals(TestingHeaderValue))
{
// fake authenticated the user
ClaimsIdentity claimsIdentity = new ClaimsIdentity();
claimsIdentity.AddClaims(new List<Claim>
{
new Claim(ClaimTypes.Name, "admin"),
new Claim(ClaimTypes.NameIdentifier, UserSeedData.AdminUserId)
});
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
context.User = claimsPrincipal;
}

await _next(context);
}
}

主体已设置并存在于具有给定 ID 的数据库中,但在调用 next(context) 后,我得到 401 Unauthorized 结果。

如何成功伪造用户身份验证并绕过 [Authorize],同时为 HttpRequest 设置当前用户?

更新:如果我像这样注册自己的 CookieAuthentication 处理程序:

app.UseCookieAuthentication(options =>
{
options.AuthenticationScheme = AuthenticatedTestRequestMiddleware.TestingCookieAuthentication;
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
});

我收到登录页面的 302 重定向。然而,当我在 TestMiddleware 中使用它时,登录工作正常 await context.Authentication.SignInAsync(TestingCookieAuthentication, ClaimsPrincipal)

最佳答案

好吧,我知道为什么它不起作用了:)

创建 ClaimsPrincipal 时,AuthenticationProvider 必须包含在主体的构造函数中。如果未提供身份验证类型,SignInAsync() 函数将失败并且无法对用户进行身份验证。

不要这样做:

ClaimsIdentity claimsIdentity = new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.Name, "admin"),
new Claim(ClaimTypes.NameIdentifier, UserSeedData.AdminUserId)
});

您必须像这样指定 AuthenticationHandler:

ClaimsIdentity claimsIdentity = new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.Name, "admin"),
new Claim(ClaimTypes.NameIdentifier, UserSeedData.AdminUserId)
}, TestingCookieAuthentication);

关于asp.net-core - 如何使用 [Authorize] 属性集成测试 ASP 5/Core Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37223397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com