50
votes

I have a rather strange issue i'm not sure how to fix or if i can even fix it.

I've done some research into the issue but can't find an answer to what's causing it.

I'm following a rather simple guide at http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on

and after enabling SSL and changing the controller to require https i get the following error:

Server Error in '/' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
Microsoft.Owin.Security.Cookies.CookieAuthenticationProvider.Exception(CookieExceptionContext context) +49
Microsoft.Owin.Security.Cookies.d__2.MoveNext() +3698 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24 Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +810 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21 Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +427 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21 Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21 Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21 Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext() +287 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__2.MoveNext() +272 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +22 Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow() +33 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +150
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +42
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +415 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34237

Turning off SSL fixes the issue, I also know that commenting out the startup.auth in app_start fixes the issue on SSL.

Does anyone know why this is happening?

16
Try putting a breakpoint in your Startup method and check exactly which lines throws this exception.BrunoLM
I've never seen this, I don't really have any ideas, just a crazy one... try clearing your cookies, maybe changing to SSL changes something with the cookies and might have corrupted something... Just a wild guess...BrunoLM
@micahhawman SSL decryption if it corrupts your cookies, owin tries to decrypt the corrupt cookies and throws the exception. Here is the fun part, instead of giving you control to do something about the bloody cookies, like establish a clean path that doesn't try to decrypt the frigging cookie attached to every request, it instead redirects your browser to a URL which posts back the corrupt cookies and you have a loop here. I like to call this THE cookie MONSTERShouvik
This is occurring for me in chrome but not IE. Will continue looking...Gina Marano

16 Answers

33
votes

Similar to Sandeep's answer, I also updated the cookie authentication provider. Except, instead of swallowing the error I threw the exception so you could see what the underlying problem was:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.  
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),

            /* I changed this part */
            OnException = (context =>
            {
                throw context.Exception;
            })
    }                
});

The underlying problem for me was that I had changed the model and forgotten to add a new migration.

19
votes

I was getting similar error but when I changed EF configuration from DropCreateDatabaseIfModelChanges< Context> to DropCreateDatabaseAlways< Context>.

I'm not sure about cause of your error but it seems like an issue in Katana Project https://katanaproject.codeplex.com/workitem/346

You can try workaround at above link or from https://katanaproject.codeplex.com/discussions/565294

This is what I did in my StartUp.Auth.cs

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
           OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager, User>(
            validateInterval: TimeSpan.FromMinutes(1),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),

           //**** This what I did ***//
            OnException = context => { }
    }
});
10
votes

Running the following updates after creating a new project worked for me:

update-package Microsoft.Owin

update-package Microsoft.Owin.Security

update-package Microsoft.Owin.Security.Cookies

I think the last one might have been enough. I am using Visual Studio 2013 (12.0.21005.1) and the ASP.Net Web Application template with Web API.

7
votes

I agree that adding "OnException = context => {}" solves exception being displayed, but the next error I saw just now may suggest a common cause, and hence a first step to try before this fix.

I now have an error informing me that the model backing by context has changed. This may mean that attempting Add-Migration and Update-Database may resolve this for other ASP.NET Identity users who encounter this, and if that fails then add the line above. This would also suggest some of the basic checks like "Can I connect to the database?" may also be worth checking if you see this Owin Security exception. Once this subsequenct error was fixed I could happily remove the OnException line and the site is still working fine.

4
votes

I had this issue too and solved it by clearing cookies.

It seems your cookie is invalid.

2
votes

The reason this exception is probably being thrown is because there is a problem creating your ApplicationDbContext.

In my case I added Migrations, and set

        Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());

And I started getting the same error as you.

Turned out that when I tried to access any object in the database, the DbContext was throwing an error, saying AspNetUsers already exists as previously I have run my code without migrations enabled, therefore the Database was created, with all the correct tables needed for Identity, and once I did EnableMigrations, and set an initialiser, it was throwing an error saying that the Table already exists.

In your case, my guess would be there is some underlying issue with the ApplicationDbContext, before the Startup, try the following before Config.Auth methods get called:

        var ctx = new ApplicationDbContext(...);
        var count = ctx.Users.Count();

See if it returns the count or throws an exception.

2
votes

Yes i had the same problem, i downloaded a database from Azure. I then change my app to use this My app had a new field that was not present in the azure backup Migrations were out of sync.

Update-Database (in package manage with migrations enabled) did the trick.

2
votes

Update-Database in Package Manager Console did the trick for me

1
votes

These answers all seem helpful and to indicate a trend that the database is messed up. I got this issue because I had updated my model and hadn't updated the database. Right now I'm calling Add-Migration and Update-Database manually each time I change the model and before I try to debug my site and I had forgotten that step.

1
votes

clear localhost cookies. if use firefox see this link. I have same error exactly and this solution here.

0
votes

I had the same problem and it happened because the SQL database is behind a firewall and you need to add your local IP every time it changes.

See this link from Microsoft for all the ways to do that:

http://msdn.microsoft.com/en-us/library/azure/jj553530.aspx

0
votes

Clearing OWIN cookie worked in my case.

0
votes

After reading some answers, trying in IE instead of Chrome and seeing no crash, I just closed Chrome and restarted the app. It worked.

0
votes

i missed to add the roles in the table [AspNetRoles]. That solved the issue.

0
votes

The reason also could be in the differences of .Net Framework versions for compiling and running the application. Just explicitly specify the version in web.config:

<httpRuntime ...... targetFramework="4.6.1" />
<compilation ...... targetFramework="4.6.1" />
0
votes

Try to remove the Migration from the project, it happened with me once I've enabled the database migration for the Identity DB

after removing the entire migration folder and rebuild the problem disappeared

it might work for you