Exception when OWIN Middleware AuthenticationHandler AuthenticateCoreAsync returns null

1.9k views Asked by At

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.

3

There are 3 answers

0
ezile On BEST ANSWER

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

0
Badrinarayanan Lakshmiraghavan On

You cannot return null but do something like this.

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

See this.

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

0
Morio On

@badri is correct.

But I would like to give more explanation.

The reason is, unlike those in tutorials, my AuthenticateCoreAsync doesn't have async modifier. returning null with async will result in some sort of empty task which is, of course, different from just a simple null, which is what I originally returned.