我想通过调用代码实现用户注销,尝试了很多办法,都存在问题。请问你们有好的解决方案吗?
//这是网上找的,但有时候可以后面就不行了
public static void RemoveCookiesAndSignOut(HttpContext Context) { // Clear sessionstate. if (Context.Session != null) { Context.Session.Clear(); } //Context.Request.Cookies.Clear(); //Context.Response.Cookies.Clear(); string cookieValue = string.Empty; if (Context.Request.Browser["supportsEmptyStringInCookieValue"] == "false") cookieValue = "NoCookie"; // Clear my owncookie. HttpCookie cookieWinSignIn = Context.Request.Cookies["Morpheus_WindowsSignedIn"]; if (cookieWinSignIn != null) { cookieWinSignIn.Value = cookieValue; Context.Response.Cookies.Remove("Morpheus_WindowsSignedIn"); Context.Response.Cookies.Add(cookieWinSignIn); } // Remove cookiesfor authentication. HttpCookie cookieSession = Context.Request.Cookies["WSS_KeepSessionAuthenticated"]; if (cookieSession != null) { cookieSession.Value = cookieValue; Context.Response.Cookies.Remove("WSS_KeepSessionAuthenticated"); Context.Response.Cookies.Add(cookieSession); } HttpCookie cookiePersist = Context.Request.Cookies["MSOWebPartPage_AnonymousAccessCookie"]; if (cookiePersist != null) { cookiePersist.Value = cookieValue; cookiePersist.Expires = new DateTime(1970, 1, 1); Context.Response.Cookies.Remove("MSOWebPartPage_AnonymousAccessCookie"); Context.Response.Cookies.Add(cookiePersist); } // Sign out. Microsoft.IdentityModel.Web.FederatedAuthentication.SessionAuthenticationModule.SignOut(); }
其实上面的思路是没问题的,知识cookie的名称似乎有点问题,通过调试你会发现有这些cookie(见图1.1),而存储身份的是FedAuth所以清除它就可以啦!
图1.1
HttpCookie ClientTokenCookie = context.Request.Cookies["FedAuth"]; if (ClientTokenCookie != null) { ClientTokenCookie.Expires = DateTime.Now.AddDays(-1); context.Response.Cookies.Add(ClientTokenCookie); }