Smashed my head against this a bit too long. How do I prevent a user from browsing a site's pages after they have been logged out using FormsAuthentication.SignOut? I would expect this to do it:
FormsAuthentication.SignOut();
Session.Abandon();
FormsAuthentication.RedirectToLoginPage();
But it doesn't. If I type in a URL directly, I can still browse to the page. I haven't used roll-your-own security in a while so I forget why this doesn't work.
Users can still browse your website because cookies are not cleared when you call FormsAuthentication.SignOut() and they are authenticated on every new request. In MS documentation is says that cookie will be cleared but they don't, bug?
Its exactly the same with Session.Abandon(), cookie is still there.
You should change your code to this:
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 is in the System.Web namespace. MSDN Reference.
Using two of the above postings by x64igor and Phil Haselden solved this:
1. x64igor gave the example to do the Logout:
You first need to Clear the Authentication Cookie and Session Cookie by passing back empty cookies in the Response to the Logout.
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 );
2. Phil Haselden gave the example above of how to prevent caching after logout:
You need to Invalidate the Cache on the Client Side via the Response.
// 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" );
}
Sounds to me like you don't have your web.config authorization section set up properly within . See below for an example.
<authentication mode="Forms">
<forms name="MyCookie" loginUrl="Login.aspx" protection="All" timeout="90" slidingExpiration="true"></forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
The key here is that you say "If I type in a URL directly...".
By default under forms authentication the browser caches pages for the user. So, selecting a URL directly from the browsers address box dropdown, or typing it in, MAY get the page from the browser's cache, and never go back to the server to check authentication/authorization. The solution to this is to prevent client-side caching in the Page_Load event of each page, or in the OnLoad() of your base page:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
You might also like to call:
Response.Cache.SetNoStore();
I've struggled with this before too.
Here's an analogy for what seems to be going on... A new visitor, Joe, comes to the site and logs in via the login page using FormsAuthentication. ASP.NET generates a new identity for Joe, and gives him a cookie. That cookie is like the key to the house, and as long as Joe returns with that key, he can open the lock. Each visitor is given a new key and a new lock to use.
When FormsAuthentication.SignOut() is called, the system tells Joe to lose the key. Normally, this works, since Joe no longer has the key, he cannot get in.
However, if Joe ever comes back, and does have that lost key, he is let back in!
From what I can tell, there is no way to tell ASP.NET to change the lock on the door!
The way I can live with this is to remember Joe's name in a Session variable. When he logs out, I abandon the Session so I don't have his name anymore. Later, to check if he is allowed in, I simply compare his Identity.Name to what the current session has, and if they don't match, he is not a valid visitor.
In short, for a web site, do NOT rely on User.Identity.IsAuthenticated without also checking your Session variables!
After lots of search finally this worked for me . I hope it helps.
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>
This works for me
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());
}
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.
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 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");
}
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.
According to Microsoft:
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.
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));
}
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.
Okay, I've been assigned with authenticating used on a login page. I've been working on this for quite a while and decided to clean up it up. The problem that I faced is one of those problems where exceptions aren't thrown, no error is generated, and everything looks okay, but when you try to use a function, it gives back a result that you don't want.
The code I used looks very similar to code from this page:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx
I've used the code from the demo in my project:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
// Create the cookie.
Response.Cookies.Add(myCookie);
So if I logged in, everything works and the below code evaluates to true:
HttpContext.Current.User.Identity.IsAuthenticated;
However, if I wanted to include subkeys to myCookie using either versions:
myCookie.Values.Add("userName", "patrick"); //version 1
myCookie.Values["userName"] = "patrick"; //version 2
Then you add to the cookies collection:
Response.Cookies.Add(myCookie);
Then refresh the page after login:
//This always set to false even after successful log on
HttpContext.Current.User.Identity.IsAuthenticated;
No clue why!
I wanted to do something where I don't have to add the encryption value to the httpcookie immediately:
//IsAuthenticated doesn't work = false
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormCookieName);
cookie.Values.Add("encryptTicket", encTicket);
It's just weird that adding subkeys don't work at all. And that I am forced to encypt a ticket in order to make it work. What I mean, is that IsAuthenticated is false all the time, logged in and authenticated or not. Can anyone try to explain what's going on with this? I have a working solution, but any insight would be helpful.
Okay, think I figured this out. It's because of how my web.config was set up for forms authentication. Using the forms tag.
The FormsAuthenticationTicket looks at that tag for specific information, and if I didn't create a cookie off of it, it wouldn't authenticate me. This was also defaulted to cookieless mode to UseCookies.
But anyways, after I create a cookie off of that, then I become authenticated and then a new session is created for me. After that, I can then provide any extra cookies I want and let the website use them as needed. But as long as that AuthCookie (in my case .ASPXAUTH) is valid, so is my authentication session.
In fact, when I tried to make a cookie session end when the browser closed, by setting the expiration date to MinValue for the cookie and the ticket, I wasn't able to authenticate either! I had to make the ticket last longer than the actual cookie so that the ticket doesn't expire before the cookie does.
The ticket information is really a configuration used to make the cookie, and after cookie creation, the browser is what defines how the cookies are used.
I am having trouble with the .Expires cookie attribute. It keeps coming back with 01/01/0001 12:00 AM, when I read the cookie back.
Here is the code. I added in the retrieve just below the save solely for debugging purposes. The save and retrieve happen in different places in the same file. I purposely did not specify a Domain, as I want the cookie to exist site wide.
The data shows up nicely, just not the expiration.
Note: I am testing under Visual Studio 2012 running under local host using .Net Framework 4.
System.Web.UI.Page oPage = this.Page;
HttpCookie oCookie = new HttpCookie("UserData");
// Set the cookie value.
oCookie.Secure = false;
oCookie["Field1"] = strField1;
oCookie["Field2"] = strField2;
oCookie.Expires = DateTime.Now.AddDays(1);
// Add the cookie.
oPage.Response.Cookies.Add(oCookie);
// Get the cookie.
oCookie = new HttpCookie("UserData");
oCookie = oPage.Request.Cookies["UserData"];
The browser will not send anything to the server except the cookie name and value. All of the other properties (expires, domain, path, httponly, ...) cannot be retrieved on requests after the cookie has been set.
The more accepted way to deal with this is to redirect the user to a login page when they try to access a protected resource and display some message along the lines of "You need to log in to view this page. If you were previously logged in, your session may have expired."
(Also note that you should be re-setting the cookie on every request, so that the user will not be logged out if they continue to use the site. It's not clear from your code whether you are doing this or not.)
I was just doing some more Google searching on my problem and saw this link, another posting here on Stackoverflow.
Cookies are always expired
I am also validating using the construct:
if (cookie != null && cookie.Expires > DateTime.Now)...
As several pointed out, expiration checking happens, if you can no longer retrieve the cookie. That is seriously dumb on whomever constructed this architecture. Yes, maybe there should be RequestCookie and ResponseCookie, the difference being ResponseCookie has no Expiry date.
The person who resopnded to me taught me that it is not just expires but other fields too.
In C# code, if using Form Authentication, You can find if cookie is persistent using below code
bool IsCookiePersistent = ((FormsIdentity)User.Identity).Ticket.IsPersistent;
Here Ticket will return the FormsAuthenticationTicket which has Expiration DateTime property.
My site works great with the backend Umbraco stuff for a user to log in and change the content etc. What i am looking to do is create a login reg section for the front facing site so users can leave comments etc.
I have created my login reg page and tried using .NET Forms Authentication but nothing seems to work! When I add the cookie, I refresh and it's not there. This method works great in non Umbraco sites, so I am assuming that I need to do something different with Umbraco.
Here is my Forms Authentication code, which doesn't seem to add cookies or SetAuthCookie:
Users Users = new Users();
ENT_User User = Users.GetUser(this.txtLogin.Text, this.txtLoginPassword.Text);
if (User.ID != Guid.Empty)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
User.Email,
DateTime.Now,
DateTime.Now.AddDays(12),
true,
User.ID.ToString(),
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie("LoginDetails", encTicket));
}
When I hover my mouse over the cookies in Debug the cookie is there, but when I refresh and come through the process again, the Cookie is not there.
Does anyone have any ideas as to what the problem is?
Thanks
You've set expiration for the ticket, but not for the cookie itself.
Try to change:
...
Response.Cookies.Add(new HttpCookie("LoginDetails", encTicket));
to:
...
var httpCookie = new HttpCookie("LoginDetails", encTicket);
httpCookie.Expires = DateTime.Now.AddDays(12);
Response.Cookies.Add(httpCookie);
consider this, If one is user of a Web application
like :
A someone visits SomeWebSite.com as a normal User (registered)
HttpCookie cookie = new HttpCookie("LastVisit");
cookie.Value = DateTime.Now.ToString();
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
B visits SomeWebSite.com, using another account as a moderator / admin
HttpCookie cookie = new HttpCookie("LastVisit");
cookie.Value = DateTime.Now.ToString();
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
Both cookies belong to same domain, but for two different Accounts. How does browser know Which cookie belongs to which account ? if we use the following code to access it.
if (Request.Cookies["LastVisit"] != null)
{
string lastTimeUserVisited = Request.Cookies["LastVisit"].Value;
}
EDIT: It's my first time ever to work on cookies.
I do appreciate your patience
I don't quite understand the question. A single browsing session won't distinguish between the two cookies. The last cookie that the server sets replaces the previous ones. Obviously, two instances of Chrome running on two different computers don't share cookies and each send their own instance of the cookie to the server in every request.
How does browser know Which cookie
belongs to which account?
It doesn't. The cookie for the second visit overwrites the cookie for the first. If you want that to be different, you have to use different cookie names, e.g. by appending the user ID to the cookie name.
If the users are logged in using the same user account on the computer, they will be using the same set of cookies.
If they are logged in using separate user accounts, they will each have their own set of user folders and thus their own browser settings and their own set of cookies.