Search code examples
owinowin-middleware

Exception when OWIN Middleware AuthenticationHandler AuthenticateCoreAsync returns null


I am try to write a custom Owin Authentication Middleware. I am currently only writing a dummy one even simpler than this.

According to this and other tutorials, it seems I could return null in AuthenticateCoreAsync of my DummyAuthenticationHandler to indicate authentication failure. So I did

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

It is ok if I return a new AuthenticationTicket with some dummy ClaimsIdentity in it, but when I return null I got this exception when I call any controller.

[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
....

I have been using Web Api 2 with Ninject but it seems even I tried commenting out Niject stuff in Startup it still won't work. and all my dependency are up to date. This is my Startup.

{
    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);
}

I have been scratching my head for a day, really would like to have some help.


Solution

  • @Morio: You can also return Task.FromResult<AuthenticationTicket>(null) instead of null without using async.