【问题标题】:Owin cookie authentication occasionally throws NullReferenceExceptionOwin cookie 身份验证偶尔会抛出 NullReferenceException
【发布时间】:2016-03-24 23:05:40
【问题描述】:

我在一个设置为 ASP.NET MVC 和 WebApi 应用程序的项目中使用 OWIN cookie 身份验证中间件(即我添加了 OWIN)。

时不时地,当我进行一些更改并开始调试时,我会遇到一个异常,每次请求都会发生一分钟左右的时间,直到网站突然再次正常工作而没有任何问题。我在本地 IIS 中托管应用程序。

System.NullReferenceException: Object reference not set to an instance of an object.
   at FooWeb.Startup.<>c.<Configuration>b__0_3(CookieExceptionContext context) in C:\ws\Foo\Main\Main\FooWeb\Startup.cs:line 138
   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.<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.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>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.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.<DoFinalWork>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)
   at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously);

我这样设置中间件:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = "Cookies",
    LoginPath = new PathString("/Account/Login"),
    LogoutPath = new PathString("/Account/Logoff"),
    CookieName = "FooWebCookieAuth",
    SlidingExpiration = true,
    ExpireTimeSpan = TimeSpan.FromMinutes(10),
    CookieSecure = CookieSecureOption.Always,

    Provider = new CookieAuthenticationProvider()
    {
        OnValidateIdentity = async context =>
        {
            // Validate access token
            if (context == null)
            {
                return;
            }

            if (context.Identity == null || !context.Identity.IsAuthenticated)
            {
                return;
            }

            if (context.Identity.Claims == null)
            {
                context.RejectIdentity();
            }

            var accessTokenClaim = context.Identity.Claims.FirstOrDefault(x => x.Type == FooClaimTypes.Token);
            var accessToken = (accessTokenClaim == null) ? null : accessTokenClaim.Value;
            if (accessToken == null)
            {
                context.RejectIdentity();
            }
            else
            {
                var client = new IntrospectionClient(
                    SecurityTokenServiceEndpoints.Introspection,
                    "FooScope", 
                    "FooSecret");
                var validationResult = await client.SendAsync(new IntrospectionRequest()
                {
                    Token = accessToken
                });

                if (validationResult.IsError || !validationResult.IsActive)
                {
                    context.RejectIdentity();
                }
            }
        },
        OnException = context =>
        {
            // exception is thrown here (so that debugging stops). Without this it just faults
            throw context.Exception;
        },
    },
});

更新 这似乎与 cookie 或至少与浏览器有关 - 因为我在浏览器中有一个会话,它会始终抛出该异常,而其他浏览器(之前也登录过) ) 可以正常访问。

【问题讨论】:

标签: c# asp.net-mvc authentication cookies owin


【解决方案1】:

我们遇到了同样的问题。几件事:

  1. 确保您使用的是至少 1.15.0 版本的 Owin.Security.Providers。
  2. 使用Kentor.OwinCookieSaver

您可能会发现以下帖子很有用:http://panuoksala.blogspot.fi/2015/03/aspnet-mvc-and-owin.html

【讨论】:

  • 两者都试过了,但都没有帮助
【解决方案2】:

与其拒绝身份,不如将其替换为匿名身份。

context.ReplaceIdentity(System.Security.Principal.WindowsIdentity.GetAnonymous());

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 2015-10-09
    • 2023-03-31
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    相关资源
    最近更新 更多