session lost on redirect - asp.net

I have a web app that is being hit by facebook. The login page retrieves the keys that I need and sets some session variables. When the server then redirects the user to the next page, the session information is lost. I’m running the IIS engine on vista ultimate at the moment, the app pools don’t matter because I’m using a state service and I’m still losing the session state. I’ve tried both the overloaded method of the response.redirect function and also adding a header to the page to force the redirect and none of this seems to work. Does anyone have any ideas of what I’m missing?
I’ve tried both of these:
Response.Headers.Add("refresh", "3;url=Dashboard.aspx")
And
Response.Redirect("Dashboard.aspx", False)
[EDIT]
So i just did a little experiment and well it turns out that when I hit the url directly from the facebook page I get the problem, but when i copy the url for the IFrame into a new browser window and try it it works fine.
[EDIT]
So I found an article on this and after addin gthe header the problem was solved (for now)
http://support.microsoft.com/kb/323752
Response.AddHeader("P3P: CP", "CAO PSA OUR")

when I hit the url directly from the facebook page I get the problem, but when i copy the url for the IFrame into a new browser window and try it it works fine.
If you're in an iframe, any cookies you set are “third-party cookies”. Third-party cookies may be subject to more stringent conditions than the normal “first-party” cookies you are setting when the user is directly on your site. This can be due to different browser default cookie handling or because the user has deliberately configured it like that. (And for good reason: many third-parties are unpleasant privacy-invading advertisers.)
In particular, in IE6+ with the default settings, you cannot set a third-party cookie unless you write a P3P policy promising that you will be a good boy and not flog your users' data to the nearest identify thief.
(In practice of course P3P is a dead loss, since there's nothing stopping the site owner from just lying. Another worthless complication that provides no actual security. Yay.)

I'd try running Fiddler and see if your session cookie is being sent properly with the response when interacting with your app via Facebook.

The session depends also on cookie support by the client. When you say the app "is being hit by facebook" are you sure that by what ever means they are "hitting" you they are supporting cookies?

Response.Redirect and refresh don't carry session. Server.Transfer() can but loses the ability to transfer to other servers/sites.

Related

Maintaining session state inside an iFrame

not sure if I'm going crazy, but I am having issues with session state inside an iFrame. Its a simple setup of one domain inside another. I dont need to share anything across the domains, all I want to do is embed a website inside another website and I want that embedded site to be able to log in / edit / update / etc using cookies / session state.
To remove all the complexities of server farms / shared sql session state etc, I created a simple html page served up by IIS that simply has an iFrame tag inside of it that call my site. All loads and is great, but the moment I try and log in, I get stuck in an endless loop of log in screens as the session is re-created with each request and I get logged out etc...
What am I missing? was there some uber browser security upgrade that cam into effect recently?
Any guidance would be awesome.
PS. I've got the p3p headers in place
Just for those experiencing the same pain as me, it turn that a cumulative update from microsoft changed the default cooke behavior from SameSite=None -> SameSite=Lax.
https://support.microsoft.com/en-us/help/4533013/kb4533013-cumulative-update-for-net-framework
to fix and I believe this is just a temporary workaround ( Message in Chrome console -> A cookie associated with a cross-site resource at was set without the SameSite attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at and ), is to add this to your web.config
<sessionState cookieSameSite="None" ..other attributes here.. />

Postman is not using cookie

I've been using Postman in my app development for some time and never had any issues. I typically use it with Google Chrome while I debug my ASP.NET API code.
About a month or so ago, I started having problems where Postman doesn't seem to send the cookie my site issued.
Through Fiddler, I inspect the call I'm making to my API and see that Postman is NOT sending the cookie issued by my API app. It's sending other cookies but not the one it is supposed to send -- see below:
Under "Cookies", I do see the cookie I issue i.e. .AspNetCore.mysite_cookie -- see below:
Any idea why this might be happening?
P.S. I think this issue started after I made some changes to my code to name my cookie. My API app uses social authentication and I decided to name both cookies i.e. the one I receive from Facebook/Google/LinkedIn once the user is authenticated and the one I issue to authenticated users. I call the cookie I get from social sites social_auth_cookie and the one I issue is named mysite_cookie. I think this has something to do with this issue I'm having.
The cookie in question cannot legally be sent over an HTTP connection because its secure attribute is set.
For some reason, mysite_cookie has its secure attribute set differently from social_auth_cookie, either because you are setting it in code...
var cookie = new HttpCookie("mysite_cookie", cookieValue);
cookie.Secure = true;
...or because the service is configured to automatically set it, e.g. with something like this in web.config:
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
The flag could also potentially set by a network device (e.g. an SSL offloading appliance) in a production environment. But that's not very likely in your dev environment.
I suggest you try to same code base but over an https connection. If you are working on code that affects authentication mechanisms, you really really ought to set up your development environment with SSL anyway, or else you are going to miss a lot of bugs, and you won't be able to perform any meaningful pen testing or app scanning for potential threats.
You don't need to worry about cookies if you have them on your browser.
You can use your browser cookies by installing Postman Interceptor extension (left side of "In Sync" button).
I have been running into this issue recently with ASP.NET core 2.0. ASP.NET Core 1.1 however seems to be working just fine and the cookies are getting set in Postman
From what you have describe it seems like Postman is not picking up the cookie you want, because it doesn't recognize the name of the cookie or it is still pointing to use the old cookie.
Things you can try:
Undo all the name change and see if it works( just to get to the root of issue)
Rename one cookie and see if it still works, then proceed with other.
I hope by debugging in this way it will take you to the root cause of the issue.

ASP.NET session lost after redirect but only with IE

Everything in italics is the original post, edits below are non-italicized
I am writing in C# using ASP.NET 4.0.
I am authenticating user credentials via SQL lookup and if valid I am storing the username in a session variable then redirecting the user back to the main page. Pretty simple.
if (!db.isValidLogin(userName, passWord))
{
//invalid login, show it!
//just some code to tell the user invalid credentials
}
else
{
//show login successful!
//update some items on the screen
Session["username"] = userName.ToUpper();
Response.Redirect("/");
}
This is not yet over SSL as it's internal development at this point.
When I use Chrome Version "25.0.1364.172 m" I am properly redirected and I am "logged in". My screen is representative of that by showing me my user name and allowing me access to features that authentication allows.
When I use (32-bit) IE 9 Version "9.0.8112.16421" with the same server side code and procedure... When I do the redirect my session variable "username" is gone. In fact the session has a count of 0 for items. BEFORE the redirect the session variable is set and it is correct.
I have the same results on a Windows Server 2008 R2 64-bit box and a Windows 7 64-bit box.
I am using a single server hosting both IIS and SQL. I am not using a session server.
I have traced it out... the code is running exactly as desired up until the redirect. Receiving credentials, executing my stored procedure to validate... setting the session variable before redirecting (I can see the session and the variable and the value is correct).. and then redirecting... and as stated, with Chrome it works EXACTLY as desired... with IE the session is lost on redirect.
I have tried this as well with no success:
Response.Redirect("/", false);
So I'm convinced that something IE is doing, maybe with setting cookies on the client, that is causing a mismatch between the browser and the server session.
Should I not be doing a response.redirect??? And if I do a response.redirect, how do I keep the session from resetting? Once again, keep in mind this doesn't happen when I use Chrome.
Frustrating...
Thanks for any help!
NEW INFO
After attempting to turn off IE caching per an answer... I decided to output the sessionID to the browser so I could see what it was.
The behavior is more direct that the login and redirect...
In IE simply refreshing the browser with F5 causes a new session to be created on the server. Each refresh I receive a NEW session ID.
Testing this with Chrome I do not get a new session ID unless I call session.abandon, timing out my session or closing and restarting the browser.
I was only calling session.abandon when the user clicked log out, but have commented out that code (just in case) to ensure that I'm not abandoning it on accident.
Somewhere between actual page refreshes IE is presenting itself to the server for a new session... ARGH.
For example:
Chrome:
Before login: myjuzrmccerk1t4eakcliq14
After login: myjuzrmccerk1t4eakcliq14
IE:
Before login: unyebuc2ikac12xnhpssy0em
After login: unyebuc2ikac12xnhpssy0em
Refreshes with F5 or Ctrl-R:
one: ptjt42fjwzgdreyyyo3cmvrs
two: s1hd5aatl5yexeuc125aqhst
three: kbpflurcdcxubux3scmdm4k5
Update 2
I have changed the site to use "State Server" for the session and started the appropriate service... There is no change in behavior.
ANSWER
Since my rep is low.. .this won't let me answer my own question for another 3 hours... but here it is..
I found a fix... through trial and error.
InProc and StateServer in sessionstate both had the same results until I added "cookieless=true"
<sessionState mode="StateServer" cookieless="true" />
This causes the session state to be consistent in both Chrome and in IE (where the problems was) and my session ID no longer changes between page refreshes. I was unable to determine WHY this happens, but it is fixed nonetheless.. Thanks Mike and antinescience for your help!
InProc and StateServer in sessionstate both had the same results until I added "cookieless=true"
This causes the session state to be consistent in both Chrome and in IE (where the problems was) and my session ID no longer changes between page refreshes. I was unable to determine WHY this happens, but it is fixed nonetheless.. Thanks Mike and antinescience for your help!
There are some other reports that indicate that IE's caching mechanism (which is widely regarded as, well, not great) may be to blame here. Can you try appending the following to your page:
// Stop Caching in IE
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
// Stop Caching in Firefox
Response.Cache.SetNoStore();
...and see if that has any effect? The other alternative is you could do:
int randomNumber = new Random().Next(1, 1000);
Response.Redirect("/?nocache=" + randomNumber);
...just for testing. Heck, you could slap the date as numeric in to test as well.
i had the same problem for couple of days now and finally i knew the reason why the session was changed each refresh, first after using the Response.Redirect( URL ,false) method i realized that i was entering the URL as AbspoluteURI as "http:// ServerIP/File/Page.aspx" , i used the AbsolutePath method instead as "~/File/Page.aspx", and my problem was solved!! the IE thinks that the server was changed when you write AbsoluteURL instead of AbsolutePath, i wish this could help
I had the same problem with a webpage which was hosted inside an IFrame. Troubleshooting showed that the ASP.NET Session cookie was lost along the way, and it only happened when using Internet Explorer. When I opened up my webpage in a separate tab in IE everything worked fine.
The problem was caused by security in Internet Explorer. It will not persist cookies unless there is a P3P HTTP header. You can see the blocked URLs by going to IE->View->Webpage privacy report..., and there choose to show "Restricted websites".
I solved the problem by adding a dummy P3P header with every request. The header looks like this;
P3P:"Bogus P3P header because Internet Explorer requires one"
This is the same approach as facebook.com uses. Their p3p header looks like this;
p3p:CP="Facebook does not have a P3P policy. Learn why here: http://(...)/p3p"
See also Cookie blocked/not saved in IFRAME in Internet Explorer
I had this issue too, this SO response solved my problem. If your hostname has underscores (which seems to be invalid), IE seems to drop the session (!).

How do you determine cookies are disabled *without* javascript and *without* redirecting?

If I disable javascript and cookies, Amazon.com detects that cookies are disabled without a redirect. If you click the cart link, there's only a get on the cart page.
I'm guessing amazon.com is most likely not using ASP.NET, but how would you accomplish detecting disabled cookies using ASP.NET without the use of javascript and redirecting? Is it possible to detect if cookies are disabled in one round trip?
I believe what you're describing is impossible. Amazon doesn't appear to do that. As proof:
Disable JavaScript
Clear your cookies (but leave them enabled)
Go here: http://www.amazon.com/gp/cart/view.html/ref=gno_cart
You'll get the message "Please Enable Cookies in your Web Browser to Continue." But if you reload the page, the message will go away, because cookies got set on the first viewing.
The reason this doesn't work is that when a page response sets cookies, the server can't tell they've been properly set until the next request. You can get around that using JavaScript, of course, but without that there's no way for the server to know in advance whether a request comes from a browser that will accept cookies.
You don't need redirect to get at the cookies. All you need is a delayed load content.
Basically, I believe the following would work:
The 'GET /index.html' response sets the Cookies (they come in the header, and are stored before index.html is received and rendered).
You can than check for cookies while serving say 'GET /TinyImage.gif' if you don't run into caching problems and respond to images dynamically.
So, the final problem, is how do you inform the user about your findings from the TinyImage request? Definitely not easily, but if you use IFrame instead of a simple tag, you can essentially have two GET requests for a single page render.
Or, you can be really, really insane and actually stall the first GET until the second GET confirms the browser settings. This is for some HTTP wizards, but if you can wrap your head around Comet (not AJAX, Comet!), it can come in handy.
It's definitely possible, just tricky. Would I try doing so in ASP.NET? Can't promise anything but it will be a neat thing to share.
I guess it may load the page in the javascript / cookies off configuration and then use javascript to do the check and set functionality to cookies enabled if needed.
Could you set a Cookie in Page_Init for instance, then see if you could read from it in Page_PreRender?
Not sure that's even possible, but that's the only way I could think of.

IE7 Classic ASP Cache

I have a classic asp website that uses Session variables to store login state ie. userid, isloggedin, etc. On logout, the session variables are reset and Session.Abandon() is called followed by a redirect to the login page. In IE7 I have noticed that after logout I can type in a previously visited url and see what appears to be a cached version of its state prior to the logout. Hitting ctl-f5 will reload from the server again and redirect to the login page. This is the behavior I want to occur even if the url is type in without the ctl-f5. Does anyone know how to get this behavior?
set the no-cache headers so that the pages do not get cached in the first place. see:
http://support.microsoft.com/kb/234067
I think mkoryak's answer (using no-cache headers) seems best. If you want certain pages to be seen only when a user is logged in, the best way is to instruct the browser to simply not cache the page. Furthermore, schemes such as tweaking cookies and using javascript do determine login state on the client are simply reinventing the wheel.
If you want to leverage some caching and your page isn't something that is constantly updating, a good compromise is to set the Response.Expires header to some value you deem appropriate (it's measured in minutes I believe).
I've had a similar problem before, but whenever I've clicked a link on that page, it's asked me to log back in.
You could try either resetting sessionID = "" or sessionID = "XYZ" and make XYZ something your code ignores on log out.
You could also try setting no-cache headers.
You could send no-cache however thats quiet a performance hit just to get what you want. I prefer Liams suggestion and ensuring that everything you do from that page requires you to be logged in, that way no one can do anything they shouldn't. What if its a email system though or similar, the people "could" view other peoples emails which are cached, in those instances then yes, not caching sensitive information is the way to go (you can't cache HTTPS pages by default for instance).
You could also include some javascript in the head which could check for the existance of a "logged in" cookie. This would run every time they loaded the page, if no cookie exists then JS could redirect you off to the login page. Not 100% fool proof but good enough. You logout page would need to clear this cookie and you login page set it.

Resources