【问题标题】:Exception when OWIN Middleware AuthenticationHandler AuthenticateCoreAsync returns nullOWIN 中间件 AuthenticationHandler AuthenticateCoreAsync 返回 null 时的异常
【发布时间】:2014-11-11 16:20:22
【问题描述】:

我正在尝试编写一个自定义的 Owin 身份验证中间件。我目前只写一个比this 更简单的虚拟。

根据this 和其他教程,似乎我可以在我的 DummyAuthenticationHandler 的 AuthenticateCoreAsync 中返回 null 以指示身份验证失败。所以我做到了

protected override Task<AuthenticationTicket> AuthenticateCoreAsync()
{
    return null;
}

如果我返回一个包含一些虚拟 ClaimsIdentity 的新 AuthenticationTicket 就可以了,但是当我返回 null 时,当我调用任何控制器时都会出现此异常

[NullReferenceException: Object reference not set to an instance of an object.]
Microsoft.Owin.Security.Infrastructure.<BaseInitializeAsync>d__0.MoveNext() +450
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +264
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +191
....

我一直在使用带有 Ninject 的 Web Api 2,但似乎即使我尝试在 Startup 中注释掉 Niject 的内容,它仍然无法正常工作。我所有的依赖都是最新的。这是我的初创公司。

{
    HttpConfiguration configuration = new HttpConfiguration();

    application.UseDummyAuthentication();
    configuration.SuppressDefaultHostAuthentication();
    configuration.Filters.Add(new HostAuthenticationFilter("dummy"));
    WebApiConfig.Register(configuration);
    application.UseNinjectMiddleware(() =>
    {
        return NinjectWebCommon.CreateKernel(WebApiConfig.CreateConfigurationDelegate());
    });
    application.UseNinjectWebApi(configuration);
}

我已经摸不着头脑了,真的很想得到一些帮助。

【问题讨论】:

    标签: owin owin-middleware


    【解决方案1】:

    @Morio:你也可以在不使用异步的情况下返回Task.FromResult&lt;AuthenticationTicket&gt;(null) 而不是null

    【讨论】:

      【解决方案2】:

      @badri 是正确的。

      但我想给出更多解释。

      原因是,与教程中的不同,我的 AuthenticateCoreAsync 没有 async 修饰符。使用异步返回 null 将导致某种空任务,当然,这与我最初返回的简单 null 不同。

      【讨论】:

        【解决方案3】:

        你不能返回 null 而是做这样的事情。

        return new AuthenticationTicket(null, (AuthenticationProperties)null);

        看这个。

        https://github.com/thinktecture/Thinktecture.IdentityModel/blob/master/source/Hawk/Owin/HawkAuthenticationHandler.cs

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-23
          • 1970-01-01
          • 2012-10-16
          相关资源
          最近更新 更多