如何在安全的 Nancy 端点中伪造身份验证



目前正在.NET中使用Nancy构建Web API。我们通过 CustomBootStrapper 保护端点:

public class CustomBootstrapper : AutofacNancyBootstrapper {
...
pipelines.BeforeRequest.AddItemToEndOfPipeline(SecurityHooks.RequiresAuthentication());

但是,我们想添加一个不安全的模块。一个简单的"hello world",用于验证 Web API 是否正确启动。因此,我们删除了上面的行,并在我们的模块中放入了以下内容:

public UsersModule(...) {
this.RequiresAuthentication();
Get("/...", async args => {

但这带来了我们的每个单元测试现在都失败的问题,因为显然现在模块只接受经过身份验证的调用。而且我不确定如何"伪造"经过身份验证的呼叫。

测试设置:

_sut = new Browser(new ConfigurableBootstrapper(with => {
var usersModule = new UsersModule(...dataservices);
with.Module(usersModule);
with.Dependency<JsonSerializer>(typeof(CamelCasedJsonSerializer));
}));

实际测试:

... 
var result = await _sut.Get($"http://localhost:80/api/users/...", with => {
with.Accept("application/json");
with.Header("Content-Type", "application/json");
});
Assert.Equal(HttpStatusCode.NotFound, result.StatusCode);

您可以在测试设置中将当前用户设置在 Nancy 上下文中。

with.RequestStartup((container, pipelines, context) => { context.CurrentUser = myTestUser; });

这将导致this.RequiresAuthentication()通过。

最新更新