ASP.NET Core 带有 Cookie 和 Windows 身份验证

4

我实现了支持Cookie的ASP.NET Core Windows身份验证

在Startup.cs中:

services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddAuthentication("CookieAuthenticationScheme")
            .AddCookie("CookieAuthenticationScheme");

关于登录:

var claims = new List<Claim>{new Claim(ClaimTypes.Name, userName)};
await httpContext.SignInAsync("CookieAuthenticationScheme", new ClaimsPrincipal(new ClaimsIdentity(claims, "CookieAuthenticationScheme")));

这个应用程序运行得还不错。但是如果一段时间没有人使用该应用程序,并且当用户再次登录应用程序时,它会引发以下错误:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost/api/User/GetCurrentUserInfo  
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[7]
      CookieAuthenticationScheme was not authenticated. Failure message: Unprotect ticket failed
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action Application.Controllers.UserController.GetCurrentUserInfo (Application) in 0.251ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 23.2483ms 401 
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost/api/User/GetCurrentUserInfo  
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[7]
      CookieAuthenticationScheme was not authenticated. Failure message: Unprotect ticket failed
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action Application.Controllers.UserController.GetCurrentUserInfo (Application) in 1.1302ms
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HLB9USN79JN9", Request id "0HLB9USN79JN9:00000002": An unhandled exception was thrown by the application.
System.ObjectDisposedException: Safe handle has been closed
   at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
   at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
   at Interop.Advapi32.LsaLookupSids(SafeLsaPolicyHandle handle, Int32 count, IntPtr[] sids, SafeLsaMemoryHandle& referencedDomains, SafeLsaMemoryHandle& names)
   at System.Security.Principal.SecurityIdentifier.TranslateToNTAccounts(IdentityReferenceCollection sourceSids, Boolean& someFailed)
   at System.Security.Principal.SecurityIdentifier.Translate(IdentityReferenceCollection sourceSids, Type targetType, Boolean& someFailed)
   at System.Security.Principal.SecurityIdentifier.Translate(IdentityReferenceCollection sourceSids, Type targetType, Boolean forceSuccess)
   at System.Security.Principal.SecurityIdentifier.Translate(Type targetType)
   at System.Security.Principal.WindowsIdentity.<GetName>b__45_0()
   at System.Security.Principal.WindowsIdentity.<>c__DisplayClass61_0.<RunImpersonatedInternal>b__0(Object <state>)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Security.Principal.WindowsIdentity.RunImpersonatedInternal(SafeAccessTokenHandle token, Action action)
   at System.Security.Principal.WindowsIdentity.RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action)
   at System.Security.Principal.WindowsIdentity.GetName()
   at System.Security.Principal.WindowsIdentity.get_Name()
   at Microsoft.AspNetCore.Authorization.DefaultAuthorizationService.GetUserNameForLogging(ClaimsPrincipal user)
   at Microsoft.AspNetCore.Authorization.DefaultAuthorizationService.<AuthorizeAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Authorization.Policy.PolicyEvaluator.<AuthorizeAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter.<OnAuthorizationAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.<Invoke>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.Extensions.UsePathBaseMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame`1.<ProcessRequestsAsync>d__2.MoveNext()
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 20.4616ms 500 

services.AddAuthentication(IISDefaults.AuthenticationScheme); 这行代码在你的程序中没有任何作用,下一行代码将其覆盖了。但这与你的错误无关。 - Tratcher
1个回答

2
Windows认证的重点是允许服务器独立操作。当您尝试使用cookie来处理身份验证时,实际上是让系统进行身份验证,然后将该身份验证存储在客户端。
该用户在IIS中的系统授权已过期,但用户自己的cookie仍显示其已通过身份验证。
我认为您实际上可能正在尝试启用Windows身份验证和匿名用户。此答案提供了如何完成此操作的详细信息。 此答案似乎也支持您不想使用cookie身份验证。
您还可以查看ASP.NET Core中Windows身份验证的设置指南,如本文所述

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接