我实现了 ASP.NET 支持Cookie的核心Windows身份验证
在创业中.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
Windows身份验证的目的是允许服务器执行自己的操作。当您尝试使用 Cookie 处理身份验证时,您实际上是让系统进行身份验证,然后存储该身份验证客户端。
系统对该用户的授权在 IIS 中即将过期,但用户自己的 Cookie 表示它们仍经过身份验证。
我相信您实际上可能要做的是启用Windows身份验证和匿名用户。这个答案有一些关于如何实现这一点的细节。
这个答案似乎也支持你在这里不需要cookie身份验证。
您可能还需要查看本文中列出的 ASP.NET Core 中的 Windows 身份验证设置指南。