FormsAuthentication.SignOut ()이 사용자를 로그 아웃하지 않습니다.
이것에 대해 너무 오랫동안 내 머리를 부 mash 버렸다. FormsAuthentication.SignOut을 사용하여 로그 아웃 한 후 사용자가 사이트 페이지를 탐색하지 못하게하려면 어떻게합니까? 나는 이것을 할 것으로 기대합니다 :
FormsAuthentication.SignOut();
Session.Abandon();
FormsAuthentication.RedirectToLoginPage();
그러나 그렇지 않습니다. URL을 직접 입력해도 페이지를 계속 탐색 할 수 있습니다. 한동안 롤업 보안을 사용하지 않아서 왜 이것이 작동하지 않는지 잊어 버렸습니다.
전화를 걸 때 쿠키가 지워지지 않고 FormsAuthentication.SignOut()
새 요청마다 인증 되기 때문에 사용자는 여전히 웹 사이트를 탐색 할 수 있습니다 . MS 문서에서 쿠키는 지워지지 만 쿠키는 지워지지 않는다고 말합니다. Session.Abandon()
쿠키 와 정확히 동일합니다 . 쿠키는 여전히 있습니다.
코드를 다음과 같이 변경해야합니다.
FormsAuthentication.SignOut();
Session.Abandon();
// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
SessionStateSection sessionStateSection = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");
HttpCookie cookie2 = new HttpCookie(sessionStateSection.CookieName, "");
cookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie2);
FormsAuthentication.RedirectToLoginPage();
HttpCookie
에 System.Web
네임 스페이스. MSDN 참조 .
에 web.config 인증 섹션이 제대로 설정되어 있지 않은 것 같습니다. 예는 아래를 참조하십시오.
<authentication mode="Forms">
<forms name="MyCookie" loginUrl="Login.aspx" protection="All" timeout="90" slidingExpiration="true"></forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
x64igor와 Phil Haselden의 위의 두 가지 게시물을 사용하여 이것을 해결했습니다.
1. x64igor가 로그 아웃을 수행하는 예제를 제공했습니다.
먼저 응답의 빈 쿠키를 로그 아웃으로 전달 하여 인증 쿠키 및 세션 쿠키 를 지워야합니다.
public ActionResult LogOff() { FormsAuthentication.SignOut(); Session.Clear(); // This may not be needed -- but can't hurt Session.Abandon(); // Clear authentication cookie HttpCookie rFormsCookie = new HttpCookie( FormsAuthentication.FormsCookieName, "" ); rFormsCookie.Expires = DateTime.Now.AddYears( -1 ); Response.Cookies.Add( rFormsCookie ); // Clear session cookie HttpCookie rSessionCookie = new HttpCookie( "ASP.NET_SessionId", "" ); rSessionCookie.Expires = DateTime.Now.AddYears( -1 ); Response.Cookies.Add( rSessionCookie );
Phil Haselden은 로그 아웃 후 캐싱을 방지하는 방법에 대해 위의 예를 제시했습니다.
응답을 통해 클라이언트 측에서 캐시 를 무효화 해야합니다 .
// Invalidate the Cache on the Client Side Response.Cache.SetCacheability( HttpCacheability.NoCache ); Response.Cache.SetNoStore(); // Redirect to the Home Page (that should be intercepted and redirected to the Login Page first) return RedirectToAction( "Index", "Home" ); }
여기서 핵심은 "URL을 직접 입력하면 ..."이라고 말합니다.
기본적으로 폼 인증에서 브라우저는 사용자의 페이지를 캐시합니다. 따라서 브라우저 주소 상자 드롭 다운에서 직접 URL을 선택하거나 입력하면 브라우저 캐시에서 페이지를 가져올 수 있으며 서버로 돌아가 인증 / 권한을 확인하지 않아도됩니다. 이에 대한 해결책은 각 페이지의 Page_Load 이벤트 또는 기본 페이지의 OnLoad ()에서 클라이언트 측 캐싱을 방지하는 것입니다.
Response.Cache.SetCacheability(HttpCacheability.NoCache);
다음과 같이 전화를 걸 수도 있습니다.
Response.Cache.SetNoStore();
나는 전에도 이것으로 고투했다.
여기에 무슨 일이 일어나고 있는지에 대한 비유가 있습니다 ... 새로운 방문자 Joe가 사이트에 와서 FormsAuthentication을 사용하여 로그인 페이지를 통해 로그인합니다. ASP.NET은 Joe의 새 ID를 생성하고 쿠키를 제공합니다. 그 쿠키는 집 열쇠와 같으며 Joe가 그 열쇠로 돌아 오는 한 자물쇠를 열 수 있습니다. 각 방문자에게는 새로운 열쇠와 새로운 자물쇠가 제공됩니다.
경우 FormsAuthentication.SignOut()
라고합니다, 시스템은 키를 분실 할 조를 알려줍니다. Joe는 더 이상 열쇠를 가지고 있지 않기 때문에 정상적으로 작동합니다.
조 다시 돌아오고, 그러나 않는 그 잃어버린 열쇠를 가지고, 그는 다시하자입니다!
내가 알 수 있듯이 ASP.NET에 문의 잠금을 변경하도록 지시하는 방법은 없습니다!
내가 이것을 살 수있는 방법은 세션 변수에서 Joe의 이름을 기억하는 것입니다. 그가 로그 아웃 할 때 세션을 포기하므로 더 이상 그의 이름이 없습니다. 나중에 허용 여부를 확인하기 위해 자신의 Identity.Name을 현재 세션과 비교하고 일치하지 않으면 유효한 방문자가 아닙니다.
즉, 웹 사이트의 경우 User.Identity.IsAuthenticated
세션 변수도 확인하지 않고 의존하지 마십시오 !
이것은 나를 위해 작동
public virtual ActionResult LogOff()
{
FormsAuthentication.SignOut();
foreach (var cookie in Request.Cookies.AllKeys)
{
Request.Cookies.Remove(cookie);
}
foreach (var cookie in Response.Cookies.AllKeys)
{
Response.Cookies.Remove(cookie);
}
return RedirectToAction(MVC.Home.Index());
}
많은 검색 후 마침내 이것은 나를 위해 일했습니다. 도움이 되길 바랍니다.
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
return RedirectToAction("Index", "Home");
}
<li class="page-scroll">@Html.ActionLink("Log off", "LogOff", "Account")</li>
The code you posted looks like it should correctly remove the forms authentication token, so it is possible that the folders/pages in question are not actually protected.
Have you confirmed that the pages cannot be accessed before a login has occured?
Can you post the web.config settings and login code that you are using?
I have been writing a base class for all of my Pages and I came to the same issue. I had code like the following and It didn't work. By tracing, control passes from RedirectToLoginPage() statement to the next line without to be redirected.
if (_requiresAuthentication)
{
if (!User.Identity.IsAuthenticated)
FormsAuthentication.RedirectToLoginPage();
// check authorization for restricted pages only
if (_isRestrictedPage) AuthorizePageAndButtons();
}
I found out that there are two solutions. Either to modify FormsAuthentication.RedirectToLoginPage(); to be
if (!User.Identity.IsAuthenticated)
Response.Redirect(FormsAuthentication.LoginUrl);
OR to modify the web.config by adding
<authorization>
<deny users="?" />
</authorization>
In the second case, while tracing, control didn't reach the requested page. It has been redirected immediately to the login url before hitting the break point. Hence, The SignOut() method isn't the issue, the redirect method is the one.
I hope that may help someone
Regards
I just tried some of the suggestions here and while I was able to use the browser back button, when I clicked on a menu selection the [Authorize] token for that [ActionResult] sent me right back to the login screen.
Here is my logout code:
FormsAuthentication.SignOut();
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
HttpCookie cookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
Although the back function on the browser took me back and displayed the secured menu (I am still working on that) I was not able to do anything that was secured in the app.
Hope this helps
I've tried most answers in this thread, no luck. Ended up with this:
protected void btnLogout_Click(object sender, EventArgs e)
{
FormsAuthentication.Initialize();
var fat = new FormsAuthenticationTicket(1, "", DateTime.Now, DateTime.Now.AddMinutes(-30), false, string.Empty, FormsAuthentication.FormsCookiePath);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat)));
FormsAuthentication.RedirectToLoginPage();
}
Found it here: http://forums.asp.net/t/1306526.aspx/1
This Answer is technically identical to Khosro.Pakmanesh. I'm posting it to clarify how his answer differs from other answers on this thread, and in which use case it can be used.
In general to clear a user-session, doing
HttpContext.Session.Abandon();
FormsAuthentication.SignOut();
will effectively log out the user. However, if in the same Request you need to check Request.isAuthenticated
(as may often happen in an Authorization Filter, for example), then you will find that
Request.isAuthenticated == true
even _after you did HttpContext.Session.Abandon()
and FormsAuthentication.SignOut()
.
The only thing that worked was doing
AuthenticationManager.SignOut();
HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
That effectively sets Request.isAuthenticated = false
.
This started happening to me when I set the authentication > forms > Path property in Web.config
. Removing that fixed the problem, and a simple FormsAuthentication.SignOut();
again removed the cookie.
It could be that you are logging in from one subdomain (sub1.domain.com) and then trying to logout from a different subdomain (www.domain.com).
I just had the same problem, where SignOut() seemingly failed to properly remove the ticket. But only in a specific case, where some other logic caused a redirect. After I removed this second redirect (replaced it with an error message), the problem went away.
The problem must have been that the page redirected at the wrong time, hence not triggering authentication.
I am having a similar issue now and I believe the problem in my case as well as the original poster is because of the redirect. By default a Response.Redirect causes an exception which immediately bubbles up until it is caught and the redirect is immediately executed, I am guessing that this is preventing the modified cookie collection from being passed down to the client. If you modify your code to use:
Response.Redirect("url", false);
This prevents the exception and seems to allow the cookie to be properly sent back to the client.
Just try to send a session variable when you press log in. And on the welcome page, first check whether that session is empty like this in the page load or in the Init Event:
if(Session["UserID"] == null || Session["UserID"] == "")
{
Response.Redirect("Login.aspx");
}
For me, the following approach works. I think if there is any error after the "FormsAuthentication.SignOut()" statement, SingOut doesn't work.
public ActionResult SignOut()
{
if (Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
return Redirect("~/");
}
return View();
}
Are you testing/seeing this behaviour using IE? It's possible that IE is serving up those pages from the cache. It is notoriously hard to get IE to flush it's cache, and so on many occasions, even after you log out, typing the url of one of the "secured" pages would show the cached content from before.
(I've seen this behaviour even when you log as a different user, and IE shows the "Welcome " bar at the top of your page, with the old user's username. Nowadays, usually a reload will update it, but if it's persistant, it could still be a caching issue.)
Doing Session.abandon() and destroying the cookie works pretty good. I'm using mvc3 and it looks like the problem occurs if you go to a protected page, log out, and go via your browser history. Not a big deal but still kinda of annoying.
Trying to go through links on my web app works the right way though.
Setting it to not do browser caching may be the way to go.
For MVC this works for me:
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return Redirect(FormsAuthentication.GetRedirectUrl(User.Identity.Name, true));
}
I wanted to add some information to help understand the problem. Forms Authentication allows for storing user data either in a cookie, or in the query string of the URL. The method your site supports can be configured in the web.config file.
The SignOut method removes the forms-authentication ticket information from the cookie or the URL if CookiesSupported is false.
At the same time, they say:
One of the HttpCookieMode values that indicates whether the application is configured for cookieless forms authentication. The default is UseDeviceProfile.
Lastly, regarding UseDeviceProfile, they say:
If the CookieMode property is set to UseDeviceProfile, the CookiesSupported property will return true if the Browser for the current Request supports both cookies and redirecting with cookies; otherwise, the CookiesSupported property will return false.
Piecing this all together, depending on the user's browser, the default configuration may result in CookiesSupported being true, which means the SignOut method doesn't clear the ticket from the cookie. This seems counter-intuitive and I don't know why it works this way -- I would expect SignOut to actually sign the user out under any circumstances.
One way to make the SignOut work by itself is to change the cookie mode to "UseCookies" (i.e. cookies are required) in the web.config file:
<authentication mode="Forms">
<forms loginUrl="~/Account/SignIn" cookieless="UseCookies"/>
</authentication>
According to my tests, doing this makes SignOut work by itself at the cost of your site now requiring cookies to function properly.
Be aware that WIF refuses to tell the browser to cleanup the cookies if the wsignoutcleanup message from STS doesn't match the url with the name of the application from IIS, and I mean CASE SENSITIVE. WIF responds with the green OK check, but will not send the command to delete cookies to browser.
So, you need to pay attention to the case sensitivity of your url's.
For example, ThinkTecture Identity Server saves the urls of the visiting RPs in one cookie, but it makes all of them lower case. WIF will receive the wsignoutcleanup message in lower case and will compare it with the application name in IIS. If it doesn't match, it deletes no cookies, but will report OK to the browser. So, for this Identity Server I needed to write all urls in web.config and all application names in IIS in lower case, in order to avoid such problems.
Also don't forget to allow third party cookies in the browser if you have the applications outside of the subdomain of STS, otherwise the browser will not delete the cookies even if WIF tells him so.
참고URL : https://stackoverflow.com/questions/412300/formsauthentication-signout-does-not-log-the-user-out
'Programing' 카테고리의 다른 글
장치 메모리에 충분한 여유 공간이 있어도 "사용 가능한 스토리지 부족" (0) | 2020.06.21 |
---|---|
LoDash : 객체 속성 배열에서 값 배열 가져 오기 (0) | 2020.06.21 |
WhatsApp 링크 공유를위한 이미지 제공 (0) | 2020.06.21 |
시간 부분을 무시하고 DATETIME 및 DATE 비교 (0) | 2020.06.21 |
라벨 태그의 너비를 어떻게 제어 할 수 있습니까? (0) | 2020.06.21 |