Why am I getting “The magic number in GZip header is not correct.” error using OWIN auth against Azure SQL

So here's my "theory". I think the Sql Azure Db is not setup correctly or the connection string is in error.

We know that when AspIdentity attempts to hit the database on Login and finds the tables are not set up it will try to create them.

I think there is a breakdown/bug in the AspIdentity code that under this circumstance swallows the exception generated from the bad connection string and thus the failed setup and continues on it's merry way trying to provide an authentication ticket to the client.

If we look into the code for Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer we find some GZip action:

 public virtual byte[] Serialize(AuthenticationTicket model)
            using (var memory = new MemoryStream())
                using (var compression = new GZipStream(memory, CompressionLevel.Optimal))
                    using (var writer = new BinaryWriter(compression))
                        Write(writer, model);
                return memory.ToArray();

So basically I think AspIdentity fails on the connection, this error is swallowed, the Owin pipeline continues processing the request but when it hits the TicketSerializer perhaps a null value or some other bogus value is passed in which Gzip tries to zip and Boom!

Weirdo YSOD output ensues.

The magic number in GZip header is not correct. Make sure you are passing in a GZip stream. 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.

AspIdentity is not properly short circuiting OWIN request processing for this particular event.

Probably utter nonsense but I'll throw it out there anyway.

I experienced a similar problem.

The Entity Framework __MigrationHistory Model column contains GZipped data. If the data in this column is corrupted then your app won't be able to unzip the data and you'll get the error.

In my case, the corruption occurred by trying to manually insert into this able.

My solution: delete corrupted __MigrationHistory rows and related DB changes and allow the app to migrate the database properly.