2017-05-31 42 views
0

我有一个owin cokies问题。我们有一个由ASP.net MVC 5支持的网站。授权是通过owin中间件。有时用户会出现500错误的白屏。我不能在当地复制它,但有几次我可以在生产中复制这种情况。浏览我发现的日志错误“System.NullReferenceException:未将对象引用设置为对象的实例。” 堆栈:owin cokies的空引用异常ASP.NET MVC 5

System.NullReferenceException:未将对象引用设置为对象的实例。 在Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer.Write(的BinaryWriter作家,AuthenticationTicket模型) 在Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer.Serialize(AuthenticationTicket模型) 在Microsoft.Owin.Security.DataHandler .SecureDataFormat 1.Protect(TData data) at Microsoft.Owin.Security.Cookies.CookieAuthenticationHandler.<ApplyResponseGrantAsync>d__f.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseCoreAsync>d__b.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseAsync>d__8.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<TeardownAsync>d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware 1.d__0.MoveNext() ---从之前位置抛出异常的堆栈跟踪结束--- 位于System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 位于System.Runtime.CompilerServices .TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware 2.<Invoke>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware 2.d__0.MoveNext() ---上一个位置的堆栈跟踪结束Ë异常被抛出--- 在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务task) 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task) 在Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware 2.<Invoke>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware 2 .d__0.MoveNext() ---从之前位置抛出异常的堆栈跟踪结束--- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (任务任务) at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.d__5.MoveNext() ---从抛出异常的上一个位置开始的堆栈跟踪结束--- 在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务task) 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task) 在Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.d__2.MoveNext() ---从以前的位置抛出异常的堆栈跟踪结束--- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean & complete dSynchronously)

Startup.Auth的一部分:

app.CreatePerOwinContext(Entities.Create); 
     app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
     app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); 
     app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); 

     //owin иногда теряет куки авторизации в response, поэтому потом возникается nullreference error 
     //здесь вызывается специальная библиотека, которая сохраняет куки авторизации (создана для фикса бага овина) 
     app.UseKentorOwinCookieSaver(); 

     app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
      LoginPath = new PathString("/newLogin"), 
      LogoutPath = new PathString("/logout"), 
      Provider = new CookieAuthenticationProvider 
      { 
       OnValidateIdentity = ctx => 
       { 
        var ret = Task.Run(async() => 
        { 
         Claim claim = null; 
         int userId = default(int); 
         User user = null; 
         try 
         { 
          claim = ctx.Identity.FindFirst("SecurityStamp"); 
          if (claim == null) return; 
          var userManager = new ApplicationUserManager(DependencyResolver.Current.GetService<IUserStore<User, int>>()); 
          userId = ctx.Identity.GetUserId<int>(); 
          user = await userManager.FindByIdAsync(userId); 

          if (user != null && user.SecurityStamp != null && user.SecurityStamp != claim.Value) 
          { 
           var exc = new Exception("ConfigureAuth->OnValidateIdentity->Reject"); 
           exc.Data.Add("claim", claim.Value); 
           exc.Data.Add("userId", userId); 
           exc.Data.Add("userStamp", user.SecurityStamp); 
           ErrorStore.LogException(exc, HttpContext.Current); 
           ctx.RejectIdentity(); 
          } 
         } 
         catch (Exception ex) 
         { 
          var exc = new Exception("ConfigureAuth->OnValidateIdentity->catch", ex); 
          if (claim != null) 
          { 
           exc.Data.Add("claim", claim.Value); 
          } 
          exc.Data.Add("userId", userId); 
          if (user!=null) 
          { 
           exc.Data.Add("userStamp", user.SecurityStamp); 
          } 
          ErrorStore.LogException(exc, HttpContext.Current); 
          ctx.RejectIdentity(); 
          return; 
         } 
        }); 
        return ret; 
       }, 
       OnApplyRedirect = ctx => 
       { 
        if (!IsApiRequest(ctx.Request)) 
        { 
         ctx.Response.Redirect(ctx.RedirectUri); 
        } 
       }, 
       OnException = (context => 
       { 
        ErrorStore.LogException(context.Exception, HttpContext.Current); 
        return; 
       }) 
      } 
     }); 

当用户得到白屏,他可以写入网址“注销”,他将被重定向到索引页。 (domain.me/ru/logout)。或者如果他清理了他的cookies,他也会被重定向到索引页面。

我安装了nuget包“Kentor.OwinCookieSaver”,因为我认为owin没有修复bug。但我认为这是徒劳的,因为我有最新版本的OWIN:

Microsoft.AspNet.Identity.Owin:2.2.1
Microsoft。Owin:3.1.0
Microsoft.Owin.Security.OAuth:3.1.0
Microsoft.Owin.Security.Cookies:3.1.0

然而Owin.Security.Providers是1.27.0版本,因为我们的不需要许多供应商(只有facebook和linkedin)。

它是一个遗留项目,所以我不深入它。

我需要一些帮助。 谢谢。

+0

你提到你有时可以在生产中重现这一点。如果你能说出你做了什么来重现,它可能会有所帮助。你喜欢删除饼干吗? –

+0

我打开了2个不同的浏览器(或在Chrome中打开Incognito)并通过第一个浏览器登录,然后在几分钟后通过第二个浏览器登录,然后再重复这种情况。有时我应该重复很​​长一段时间,很难重现这个错误。 @RuardvanElburg –

回答