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

时间:2018-05-29 13:59:13

标签: c# .net-core 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);

1 个答案:

答案 0 :(得分:0)

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

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

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