I'm writing an asp.net application and I am saving the cookies correctly (stored in internet files). When I open the file it contains: access_token mylongalphanumberictoken /domainname (no spaces between them).
The problem is that when I check the client for a cookie, I receive null. Can anyone tell me why this is happening and how do i fix it?
public void createCookie(string tokenVal)
{
authCookie = new HttpCookie("access_token",tokenVal);
authCookie.Expires = DateTime.Now.AddDays(60.00); //Token expires in 60 days
authCookie.Domain = ServerDomain.Authority;
}
check if the client has cookies like this:
if (Request.Cookies["access_token"] != null)
{
currentCookieStore.authCookie = Request.Cookies["access_token"];
}
EDIT: im using: currPage.Response.Cookies.Add(newTokenCookie.OauthCookie) ;
to add the cookies. ServerDomain is the location of my webserver so its machinename.domain
The answer is to add a P3P header to prevent IE from blocking your cookies.
Solution here:
Explanation: Cookie blocked/not saved in IFRAME in Internet Explorer
How to: http://social.msdn.microsoft.com/Forums/windowsazure/en-US/4f74156a-54a0-468b-8496-85913094fc34/issue-while-adding-http-response-header-to-a-site-hosted-in-azure-web-role-running-with-more-than?forum=windowsazuremanagement
I am working on a piece of code that directly relates to redirecting a page to a login screen if the user id is non existent.
The code is currently written as:
this.currentContext = System.Web.HttpContext.Current;
this.User = new BLL.User(); // base constructor
this.User.RestoreSession(currentContext.Session); // attempt to connect to DB with current session
if (this.UserID < 1)
{
currentContext.Response.Redirect("~/Default.aspx?url=" + currentContext.Request.Url.AbsoluteUri.ToBase64());
}
Which work's just fine.
However in a new addon we are building into the system it uses iframes which is okay but the login screen happens in the iframe and we need to make the parent window redirect to the login window then redirect back to page we were on.
My question is what would be the best way of doing this without rewriting the entire login process?
The best way to do redirect without rewriting the login process is to replace iframes with Ajax calls. Check this: How can I use AJAX as an alternative to an iframe?
I want to:
Login to a website
Save Cookies
Give user a choice to do A, B or C
A,B and C all require being logged in.
Each will open a FirefoxDriver and do their own thing
What i want to do, is login ONCE, save the cookies from that, and add them to any other FirefoxDriver i want to open.
Right now I'm trying to save the cookies in
public ReadOnlyCollection<Cookie> Cookies { get; set; }
which is the result of
WebDriver.Manage().Cookies.AllCookies;
Assuming login worked and cookies were saving in the above, I have this:
WebDriver = new FirefoxDriver();
WebDriver.Navigate().GoToUrl("http://www.example.com");
if (cookies != null)
{
var s = WebDriver.Manage().Cookies; //Logged out cookies
WebDriver.Manage().Cookies.DeleteAllCookies(); //Delete all of them
var sd = WebDriver.Manage().Cookies; //Make sure theyre deleted
foreach (var cookie in cookies)
{
WebDriver.Manage().Cookies.AddCookie(cookie);
}
var ss = WebDriver.Manage().Cookies;
WebDriver.Navigate().GoToUrl("http://example.com/requiresloginpage");
}
The problem is, howevering over "ss" in this case, gives this exception error
AllCookies = 'ss.AllCookies' threw an exception of type
'OpenQA.Selenium.WebDriverException'
base {System.Exception} = {"Unexpected problem getting cookies"}
InnerException = {"Cookie name cannot be null or empty string\r\nParameter name: name"}
I'm passing 8 cookies (total number when youre logged in) - and all of them seem set and ok. Not sure what I'm doing wrong
In order to save cookies, you should tell selenium to use a specified profile. For some reason I can't get it to use my normal Chrome profile, but this solution will allow you to log in one time, and afterward, selenium will remember cookies.
ChromeOptions options = new ChromeOptions();
options.AddArguments(#"user-data-dir=C:\Users\YOU\AppData\Local\Google\Chrome\User Data\NAMEYOUCHOOSE");
//specify location for profile creation/ access
ChromeDriver driver = new ChromeDriver(options);
Simply put, this code creates a save location for a profile, which does include cookies.
using this code, it is not necessary to write code that saves or loads cookies, Chrome will handle that.
Please note that the location where chrome saves your profiles may be different than mine, and I have only successfully used a directory that leads to the same location as my regular Chrome profile. This profile exists in the form of a folder, not a file.
Generally Selenium do not support cross-session cookies.
Most easy way is to use Serialization.
You need to create wrapper class around selenium's cookie and make it serializable. And create class CookiesManager where will be 2 methods: SaveSession() -- to save and RestoreSession() - to restore from serialized file.
Another way is to save some cookies information into some temp cookies file. Like.... Csv or XML.
Sample of this way you can see here: Keep user logged in - save cookies using web driver
but only for c#.
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.
I have a folder in my webserver with some aspx pages that can only be accessed if a certain cookie exists.
On th page_load event i'm checking whether this cookie exists, if not redirect to Default.aspx. This works great with browsers such as Google Chorme and FireFox (3, I have not tested 2 yet). But... for some reason IE will send some sort of cookie still as my website thinks that there is a cookie available of some sorts..
So I added a button to my page to delete the cookie. but the cookie does not exist according to my code (which is correct). My assumption then was that IE caches the page. So after wiping the cache does my page code work properly and you get redirected to Default.aspx.
Is there some sort of way to deny access to the folder if that cookie does not exist, so that IE isn't showing a page that doesn't work?
It's kind of hard to explain.
My cookie checking code is this:
protected void Page_Load(object sender, EventArgs e)
{
{
SimpleAES decrypt = new SimpleAES();
//Check for Authentication Cookie
HttpCookie auth_Cookie = new HttpCookie("WEB_AUTH");
auth_Cookie = Request.Cookies["WEB_AUTH"];
if (auth_Cookie != null)
{
//Some code to execute if Cookie exists and holds correct values
}
else
{
//If there isn't a cookie, redirect to login.aspx
Response.Redirect("~/Default.aspx");
}
}
}
Any help provided would be welcome!
Thanks
ADDED
I just want these pages in folder 'XXX' not be displayed if that cookie is not available. but IE loads the page from it's local cache rather than check whether it can actually load this. What to do?
EDIT
The pages in the folder 'XXX' have 1 master page which is where the Cookie checking code resides in.
You need to prevent browser from caching the page. You should set Response.Cache according to your requirements ( http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cache(v=VS.100).aspx).
Note that browser in theory can completely ignore your caching headers and load page from its own cache anyway, in practice all browsers respect caching headers.