FormsAuthentication.SignOut Not Working With Custom-Domain Cookie - asp.net

Title should say it all.
Here's the code to set the cookie:
// snip - some other code to create custom ticket
var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encodedTicket);
httpCookie.Domain = "mysite.com";
httpContextBase.Response.Cookies.Add(httpCookie);
Here's my code to signout of my website:
FormsAuthentication.SignOut();
Environment:
ASP.NET MVC 3 Web Application
IIS Express
Visual Studio 2010
Custom domain: "http://localhost.www.mysite.com"
So when i try and log-off, the cookie is still there. If i get rid of the httpCookie.Domain line (e.g default to null), it works fine.
Other weird thing i noticed is that when i set the domain, Chrome doesn't show my cookie in the Resources portion of developer tools, but when i dont set the domain, it does.
And secondly, when i actually create the cookie with the custom domain, on the next request when i read in the cookie from the request (to decrypt it), the cookie is there, but the domain is null?
I also tried creating another cookie with the same name and setting the expiry to yesterday. No dice.
What's going on? Can anyone help?

I believe if you set the domain attribute on the forms element in you web.config, to the same as the one in your custom cookie, it should work. (EDIT: that approach won't work because the SignOut method on FormsAuthentication sets other flags on the cookie that you are not, like HttpOnly) The SignOut method basically just sets the cookie's expiration date to 1999, and it needs the domain to set the right cookie.
If you can't hardcode the domain, you can roll your own sign out method:
private static void SignOut()
{
var myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
myCookie.Domain = "mysite.com";
myCookie.Expires = DateTime.Now.AddDays(-1d);
HttpContext.Current.Response.Cookies.Add(myCookie);
}
An authentication cookie is just a plain cookie; so you would remove it the same way you would any other cookie: expire it and make it invalid.

I had a similar problem. In my case, I was storing some userData in the AuthCookie and experienced the same effects as described above, and upon authentication at each request, reading the cookie and putting the userData in a static variable. It turned out in my case that the data was being persisted in the application. To get around it, I had to first clear my static variable, and then expire the cookie. I used the following in the LogOff method of my AccountController:
AuthCookie.Clear(); //STATIC CLASS holding my userdata implemented by me.
Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddYears(-1);
Response.Cookies[FormsAuthentication.FormsCookieName].Value = null;
return RedirectToAction("Index", "Home");
Hope this helps.
UPDATE
On a hunch after submitting, I replaced the middle two lines with:
FormsAuthentication.SignOut();
... and it worked fine where it didn't before.
Note:
AuthCookie.Clear();
... does not touch the AuthCookie, it just resets the static class I wrote to default values.
Again, hope this helps.

Related

.net mvc some users missing cookies

I am using custom forms authentication for an asp.net MVC application, and am having problems with some users seemingly not having cookies. The custom forms authentication method we are using is similar to this - custom forms authentication. Essentially, we create a custom Principal and Identity, serialize it, and store it in the UserData property of the FormsAuthenticationTicket :
Login
MyCustomPrincipal principal = new MyCustomPrincipal(user);
DateTime expiration = DateTime.Now.AddMinutes(30);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
u.Username,
DateTime.Now,
expiration,
true,
JsonConvert.SerializeObject(principal));
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
cookie.Expires = expiration;
Response.Cookies.Set(cookie);
We then grab the auth cookie in the Application_AuthenticateRequest event of global.asax.
global.asax - Application_AuthenticateRequest
// Get the authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
// If the cookie can't be found, don't issue the ticket
if (authCookie == null) return;
// Get the authentication ticket and rebuild the principal
// & identity
FormsAuthenticationTicket authTicket =
FormsAuthentication.Decrypt(authCookie.Value);
MyCustomPrincipal userPrincipal = new MyCustomPrincipal(authTicket.UserData);
DateTime expiration = DateTime.Now.AddMinutes(30);
FormsAuthenticationTicket newAuthTicket = new FormsAuthenticationTicket(
1,
((MyCustomIdentity)userPrincipal.Identity).Username,
DateTime.Now,
expiration,
true,
JsonConvert.SerializeObject(userPrincipal));
authCookie.Value = FormsAuthentication.Encrypt(newAuthTicket);
authCookie.Expires = expiration;
HttpContext.Current.Response.Cookies.Set(authCookie);
Context.User = userPrincipal;
web.config
<authentication mode="Forms">
<forms loginUrl="~/Home/Index" timeout="29" name="MYFORMSAUTH" cookieless="UseCookies"/>
</authentication>
This works fine for the large majority of users, however, there are some users who appear to be getting no authorization cookie set. I did a few tests to add more information to my Elmah error logs to see if I could find out more about the problem.
First, I tried setting some test cookies before and after the setting of the authcookie in the Login method. These cookies did not appear in the Elmah logs, so it appears adding cookies of any kind in this method is not working. However, there are other cookies in the logs, including the ASP.NET_SessionId, a google analytics cookie, and sometimes there are even other cookies I have set at other locations in the application (probably from a previous session)
Second, I tried adding some info to the session from the login action, and including it in the error log if the authcookie was not found on the next action. I included the length of the cookie (the name's length + the encrypted value's length) as well as the time of the attempted login. Both of these are added only if the user's credentials are valid, and the application attempts to add the auth cookie. I do see these values in the error logs being produced. The length is always greater than 0, and I haven't seen any bigger that about 2300, so I don't think size is an issue. And the attempted login is identical to the time that the error occurs - so the session variables should have been set immediately before the error occurred (cookies went missing).
A few more notes -
There doesn't appear to be any browser in particular that seems to be causing the error more (though it is possible it occurs more on mobile browsers)
Again, the site seems to work for the large majority of users, and of course we cannot reproduce the issue
Since I am not seeing the test cookies, I am guessing that for some reason no cookies are being set from the login method at that time (though I can see other cookies set elswhere that would imply previous successful logins)
The http referer in the elmah logs is usually set to the login page, which implies that users are probably not hitting the offending page without logging in (at least some of the time) - the state of the session variables seems to support that assumption
I'm often seeing multiple of these errors in a row (separated by a minute or so) - implying that the issue isn't resolved with repeated login attempts (not sure why it would be)
It appears users who have this issue continue to have the issue. In other words, it doesn't appear to be "luck of the draw" - but something either with the user's account (which the cookie length session variable implies it is serializing correctly), or the client browser.
I've heard of at least one user who was able to log in on a mobile device, but not their desktop
In total the site probably uses 10 or so cookies (including all of the various test cookies that have been added) - before adding the test cookies it used about 4 including the auth cookie. Also, when the bug occurs, there appear to usually only be 2 or 3 cookies in the request, so I don't think number of cookies is an issue.
At this point I'm willing to try almost anything. I tried setting up using the custom identity stored in the session as a backup, but couldn't get that working, so even if anyone has ideas about how to implement that (if possible) it would be appreciated (if this is off topic then I can remove it).
Sorry for the walls of text, but I just wanted to point out all of the potential issues we have investigated and most likely ruled out.
EDIT
It appears there may be another potentially related issue. I'm seeing error logs which lead me to believe that the "IsAuthenticated" attribute of some Identities is being set to false when it should not be. We do initialize this to false, and set it to true after the user answers a security question. When we set it to true, it should update the principle and the authentication ticket / cookie. I'm not sure if this is happening because of some issue with how I am deserializing the custom principal or not.
is server side caching enabled?
is I remember exactly I had similar problem and the cause was the server side caching (misconfigured) and the server side code was not executed but the client reaches the page.
in addition in my side there was a bug (iis bug on caching enabled on dynamic page) that in some situations the session cookie is sent to more than 1 client and this causes unexpected result.
this can explain your non logging behavior and the cookie not present on client.
Regards
So I've sort of given up and decided to use the Session to store my principal, and check it when I don't see the authentication cookie. I can do this somewhat easily by creating a custom Authorize attribute, and checking the session there. I haven't pushed this to production yet, so I'm not 100% sure this will work around the issue, but preliminary testing would suggest it will suffice.
CustomAuthorizeAttribute
public class MyCustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// Get the authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName];
// If the cookie can be found, use the base authentication
if (authCookie != null)
{
base.OnAuthorization(filterContext);
}
else
{
// The cookie is not found, check the session for the principal
var p = HttpContext.Current.Session[FormsAuthentication.FormsCookieName];
if (p != null)
{
// there is a principal object in the session
MyCustomPrincipal principal = (MyCustomPrincipal)p;
HttpContext.Current.User = principal;
// we've loaded the principal, now just do the base authorization
base.OnAuthorization(filterContext);
}
else
{
// there is no principal object in the cookie or the session, the user is not authenticated
HandleUnauthorizedRequest(filterContext);
}
}
}
}
Once we've set the current principal appropriately using the custom authorize attribute, we can then just use the base authorization, so we don't have to worry about implementing that functionality ourselves. The base authorization should check the current principal and authorize based off of that.
I'm not going to mark this as an answer, because it doesn't really solve the underlying issue, but I thought I'd provide it as a potential workaround in case someone else stumbled along a similar issue.

Cookie seems to never exist

I am facing a weird issue regarding cookies: I am trying to set up a cookie with the user id the first time the user logs into the application, and next time, if the cookie exists, not require the user authentication again.
For this I am using the code below:
to set the cookie:
HttpCookie userCookie = new HttpCookie("UserCookie");
userCookie.Value = UserId.ToString();
userCookie.Expires = DateTime.Now.AddHours(1);
System.Web.HttpContext.Current.Response.Cookies.Add(userCookie);
to get the cookie:
HttpCookie UserCookie = System.Web.HttpContext.Current.Request.Cookies["UserCookie"];
if (UserCookie != null)
{
// redirect the user to another screen inside the application
}
The weird thing is that my cookie seems not to exist and the user is prompted with the log in screen all the time. When I try to use debugging, it appears to me that the cookie is not null, but it's got an empty string value. What can I do about this?
Many thanks!
Are you trying to GET the cookie in the same code that SETS the cookie? If so, the cookie won't exist. Cookie gets SET on the users browser when the page has been delivered.
Also, can you confirm UserID.ToString() isn't actually an empty string..?
To test properly, set the cookie on page A, then redirect to page B and GET the cookie here.

Setting domain on Authentication Cookie breaks authentication in MVC

I'd like to share authentication between two websites as I slowly rewrite functionality from the old one and transition to the new one. I found an answer on here to do that: Sharing Authentication between ASP.NET sites
The problem is that when I set the domain property, the authentication cookie stops working. The user still is authenticated succesfully, and the cookie appears to be created and set correctly... but when the site is loaded the user is forced to the login screen.
I'm using the standard MVC generated authentication code, which works fine as long as domain is not set:
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
If I debug and look at the FormsAuthentication object it looks like the domain and everything else is set correctly.
So what could be causing this, and how do I fix it?
Could you please try with setting a machine key in your web.config? It must be the same within every web site.
http://aspnetresources.com/tools/machineKey

ASP.NET: Session.SessionID changes between requests

Why does the property SessionID on the Session-object in an ASP.NET-page change between requests?
I have a page like this:
...
<div>
SessionID: <%= SessionID %>
</div>
...
And the output keeps changing every time I hit F5, independent of browser.
This is the reason
When using cookie-based session state, ASP.NET does not allocate storage for session data until the Session object is used. As a result, a new session ID is generated for each page request until the session object is accessed. If your application requires a static session ID for the entire session, you can either implement the Session_Start method in the application's Global.asax file and store data in the Session object to fix the session ID, or you can use code in another part of your application to explicitly store data in the Session object.
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.sessionid.aspx
So basically, unless you access your session object on the backend, a new sessionId will be generated with each request
EDIT
This code must be added on the file Global.asax. It adds an entry to the Session object so you fix the session until it expires.
protected void Session_Start(Object sender, EventArgs e)
{
Session["init"] = 0;
}
There is another, more insidious reason, why this may occur even when the Session object has been initialized as demonstrated by Cladudio.
In the Web.config, if there is an <httpCookies> entry that is set to requireSSL="true" but you are not actually using HTTPS: for a specific request, then the session cookie is not sent (or maybe not returned, I'm not sure which) which means that you end up with a brand new session for each request.
I found this one the hard way, spending several hours going back and forth between several commits in my source control, until I found what specific change had broken my application.
In my case I figured out that the session cookie had a domain that included www. prefix, while I was requesting page with no www..
Adding www. to the URL immediately fixed the problem. Later I changed cookie's domain to be set to .mysite.com instead of www.mysite.com.
my problem was that we had this set in web.config
<httpCookies httpOnlyCookies="true" requireSSL="true" />
this means that when debugging in non-SSL (the default), the auth cookie would not get sent back to the server. this would mean that the server would send a new auth cookie (with a new session) for every request back to the client.
the fix is to either set requiressl to false in web.config and true in web.release.config or turn on SSL while debugging:
Using Neville's answer (deleting requireSSL = true, in web.config) and slightly modifying Joel Etherton's code, here is the code that should handle a site that runs in both SSL mode and non SSL mode, depending on the user and the page (I am jumping back into code and haven't tested it on SSL yet, but expect it should work - will be too busy later to get back to this, so here it is:
if (HttpContext.Current.Response.Cookies.Count > 0)
{
foreach (string s in HttpContext.Current.Response.Cookies.AllKeys)
{
if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid")
{
HttpContext.Current.Response.Cookies[s].Secure = HttpContext.Current.Request.IsSecureConnection;
}
}
}
Another possibility that causes the SessionID to change between requests, even when Session_OnStart is defined and/or a Session has been initialized, is that the URL hostname contains an invalid character (such as an underscore). I believe this is IE specific (not verified), but if your URL is, say, http://server_name/app, then IE will block all cookies and your session information will not be accessible between requests.
In fact, each request will spin up a separate session on the server, so if your page contains multiple images, script tags, etc., then each of those GET requests will result in a different session on the server.
Further information: http://support.microsoft.com/kb/316112
My issue was with a Microsoft MediaRoom IPTV application. It turns out that MPF MRML applications don't support cookies; changing to use cookieless sessions in the web.config solved my issue
<sessionState cookieless="true" />
Here's a REALLY old article about it:
Cookieless ASP.NET
in my case it was because I was modifying session after redirecting from a gateway in an external application, so because I was using IP instead on localhost in that page url it was actually considered different website with different sessions.
In summary
pay more attention if you are debugging a hosted application on IIS instead of IIS express and mixing your machine http://Ip and http://localhost in various pages
In my case this was happening a lot in my development and test environments. After trying all of the above solutions without any success I found that I was able to fix this problem by deleting all session cookies. The web developer extension makes this very easy to do. I mostly use Firefox for testing and development, but this also happened while testing in Chrome. The fix also worked in Chrome.
I haven't had to do this yet in the production environment and have not received any reports of people not being able to log in. This also only seemed to happen after making the session cookies to be secure. It never happened in the past when they were not secure.
Update: this only started happening after we changed the session cookie to make it secure. I've determined that the exact issue was caused by there being two or more session cookies in the browser with the same path and domain. The one that was always the problem was the one that had an empty or null value. After deleting that particular cookie the issue was resolved. I've also added code in Global.asax.cs Sessin_Start method to check for this empty cookie and if so set it's expiration date to something in the past.
HttpCookieCollection cookies = Response.Cookies;
for (int i = 0; i < cookies.Count; i++)
{
HttpCookie cookie = cookies.Get(i);
if (cookie != null)
{
if ((cookie.Name == "ASP.NET_SessionId" || cookie.Name == "ASP.NET_SessionID") && String.IsNullOrEmpty(cookie.Value))
{
//Try resetting the expiration date of the session cookie to something in the past and/or deleting it.
//Reset the expiration time of the cookie to one hour, one minute and one second in the past
if (Response.Cookies[cookie.Name] != null)
Response.Cookies[cookie.Name].Expires = DateTime.Today.Subtract(new TimeSpan(1, 1, 1));
}
}
}
This was changing for me beginning with .NET 4.7.2 and it was due to the SameSite property on the session cookie. See here for more info: https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/
The default value changed to "Lax" and started breaking things. I changed it to "None" and things worked as expected.
Be sure that you do not have a session timeout that is very short, and also make sure that if you are using cookie based sessions that you are accepting the session.
The FireFox webDeveloperToolbar is helpful at times like this as you can see the cookies set for your application.
Session ID resetting may have many causes. However any mentioned above doesn't relate to my problem. So I'll describe it for future reference.
In my case a new session created on each request resulted in infinite redirect loop. The redirect action takes place in OnActionExecuting event.
Also I've been clearing all http headers (also in OnActionExecuting event using Response.ClearHeaders method) in order to prevent caching sites on client side. But that method clears all headers including informations about user's session, and consequently all data in Temp storage (which I was using later in program). So even setting new session in Session_Start event didn't help.
To resolve my problem I ensured not to remove the headers when a redirection occurs.
Hope it helps someone.
I ran into this issue a different way. The controllers that had this attribute [SessionState(SessionStateBehavior.ReadOnly)] were reading from a different session even though I had set a value in the original session upon app startup. I was adding the session value via the _layout.cshtml (maybe not the best idea?)
It was clearly the ReadOnly causing the issue because when I removed the attribute, the original session (and SessionId) would stay in tact. Using Claudio's/Microsoft's solution fixed it.
I'm on .NET Core 2.1 and I'm well aware that the question isn't about Core. Yet the internet is lacking and Google brought me here so hoping to save someone a few hours.
Startup.cs
services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder
.WithOrigins("http://localhost:3000") // important
.AllowCredentials() // important
.AllowAnyMethod()
.AllowAnyHeader(); // obviously just for testing
}));
client.js
const resp = await fetch("https://localhost:5001/api/user", {
method: 'POST',
credentials: 'include', // important
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
Controllers/LoginController.cs
namespace WebServer.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpPost]
public IEnumerable<string> Post([FromBody]LoginForm lf)
{
string prevUsername = HttpContext.Session.GetString("username");
Console.WriteLine("Previous username: " + prevUsername);
HttpContext.Session.SetString("username", lf.username);
return new string[] { lf.username, lf.password };
}
}
}
Notice that the session writing and reading works, yet no cookies seem to be passed to the browser. At least I couldn't find a "Set-Cookie" header anywhere.

ASP.NET cookie expiration time is always 1/1/0001 12:00 AM

I'm setting the cookie expiration using the following code:
// remove existing cookies.
request.Cookies.Clear();
response.Cookies.Clear();
// ... serialize and encrypt my data ...
// now set the cookie.
HttpCookie cookie = new HttpCookie(AuthCookieName, encrypted);
cookie.Expires = DateTime.Now.Add(TimeSpan.FromHours(CookieTimeOutHours));
cookie.HttpOnly = true;
response.Cookies.Add(cookie);
// redirect to different page
When I read the cookie timeout in the other page I'm getting 1/1/0001 12:00 AM. If someone can help me figure out the problem, I'll appreciate it. I'm using ASP.NET 3.5
ok. after reading the links from Gulzar, it appears that I cannot check cookie.Expires on the HttpRequest at all? Because the links seem to suggest that cookie.Expires is always set to DateTime.MinValue because the server can never know the actual time on the client machine? So this means I have to store the time inside the cookie myself and check it? Is my understanding correct?
thanks
Shankar
The problem here doesn't really lie with ASP.NET but with the amount of information that is provided in the http request by browsers. The expiry date would be unobtainable regardless of the platform you are using on the server side.
As you have summarised yourself in your question the Expires property of the HttpCookie object that is provided by the HttpRequest object is always set to 1/1/0001 12:00 AM.
This is because this expiry information, as well as the properties such as domain and path, are not passed by the browser to the server when it sends a request. The only cookie information that is sent is the name and value(s). Therefore cookies in the request will have default values for these 'missing' fields as they are unknown on the server side.
I would guess the reason behind this is that the expiry, domain and path attributes of a cookie are only intended to be used by the browser when it is making a decision as to whether it should pass a cookie in a request or not and that the server is only interested in the name and value(s).
The work around you have suggested of duplicating the expiry time as another value of the cookie is a way to get the behaviour you are looking for.
At first I also disappointed why Request cookie doesn't have the actual Expires value. After debugging the http by using Fiddler2. I know that .NET was not wrong, instead, http protocol is the answer why Request cookies behaving like that.
If you use Fiddler between your app and the browser. You can see the Response cookie sent correctly to browser with all domain, path, expires, secure and httponly. However next Request cookie in http cookie header doesn't have the expires value, it only cookie name and value. Browser responsible to send this request header and I believe that is because http protocol. The reason why is because to minimize size and web server doesn't need to check it since they actually set all the values. They should notice.
So you no need to check the expires value on web request since you already know the date. Just, if you receive the cookie back that means the cookie is not yet expired. Once you set the expires, browser will handle the expiry. If you want to change the expires, just set the new value on the response.
CallMeLaNN
To solve this problem I add a claim to the principal which I can then read back and display the cookie expiry time to the user as follows:
public static void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString(string.Format("~/Login.aspx"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SetExpiryClaim
}
});
app.MapSignalR();
}
private static Task SetExpiryClaim(CookieValidateIdentityContext context)
{
var contextExpireUtc = context.Properties.ExpiresUtc;
var claimTypeName = "contextExpireUtc";
var identity = context.Identity;
Claim contextExpiryClaim;
if (identity.HasClaim(c => c.Type == claimTypeName))
{
contextExpiryClaim = identity.FindFirst(claimTypeName);
identity.RemoveClaim(contextExpiryClaim);
}
contextExpiryClaim = new Claim(claimTypeName, contextExpireUtc.ToString());
context.Identity.AddClaim(contextExpiryClaim);
return Task.FromResult(true);
}
Then you are able to retrieve the expiry time later from the ClaimsPrinciple by
ClaimsPrincipal principle = Thread.CurrentPrincipal as ClaimsPrincipal;
DateTime contextExpiry = principle.Claims.First(p => p.Type == "contextExpireUtc").Value.AsDateTime();
The version problem discussed in the link was not helpful. Basically ASP.NET cookie sucks. I had to store the expiration date time inside the cookie myself and check it in every request.
I had a similar problem when testing with an Iphone. The problem was due to the Iphone having the wrong date time set on the device, thus setting the cookie expire date to datetime.now.adddays(-1) did not expire the cookie
A request from a browser sends only the name and value of the cookies as follows:
GET /sample_page.html HTTP/2.0
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry
So this is not a problem in ASP.NET. And as mentioned in some answers and comments the expiration date is to determine whether to send that cookie to the server or not. So if the cookie was expired, it would be null on the server.
Also the workaround would be storing another value on that cookie that determines the expiry date (if you really need it)
Reference: Using HTTP cookies

Resources