This project has moved and is read-only. For the latest updates, please go here.

Exception when AuthenticationHandler.AuthenticateCoreAsync returns null

Nov 11, 2014 at 8:33 PM
Edited Nov 11, 2014 at 8:42 PM
I am try to write a custom Owin Authentication Middleware. I am currently only writing a dummy AuthenticationHandler.

According to others, it seems I could return null in AuthenticateCoreAsync of my DummyAuthenticationHandler to indicate authentication failure. So I did this
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();

    configuration.Filters.Add(new HostAuthenticationFilter("dummy"));
    application.UseNinjectMiddleware(() =>
        return NinjectWebCommon.CreateKernel(WebApiConfig.CreateConfigurationDelegate());
I have been scratching my head for a day, really would like to have some help.
Nov 12, 2014 at 5:54 PM
Ah, I see your problem. Methods that return Task must not return null tasks. You can return Task.FromResult(null), or make your method signature async Task so it will handle the conversion for you.
Nov 12, 2014 at 10:02 PM
Edited Nov 12, 2014 at 10:05 PM
@Tratcher is correct. Adding async modifier to my AuthenticateCoreAsync solved the problem.
Nov 12, 2014 at 10:05 PM
Sorry, that should have said Task.FromResult<object>(null);