I am sending a HTTPWebRequest from C# code and in response I am getting a cookie containing session ID. I am not able to locate the cookie in the public/non public members of response. However fiddler is capturing the cookie and its path is "/". Can anyone please tell me where should I look for this cookie? I have checked the folder "C:\Users\UserName\AppData\Roaming\Microsoft\Windows\Cookies" and its not there.
Cookies may be physically stored in different locations, depending on the browser.
I think you're better off getting the HttpWebRequest working with cookies.
See the answer to this question regarding adding a CookieContainer to the request object.
Every browser store cookies onto different locations
For example
Cookie information is stored in the profile folder, in two files.
Starting with Firefox 3.0 and SeaMonkey 2.0 the cookie information is
stored in the files cookies.sqlite and permissions.sqlite. In Firefox
2 or below and Mozilla Suite/SeaMonkey 1.x, cookies are stored in the
cookies.txt file and cookie site permissions are stored in the
hostperm.1 file. File Description cookies.sqlite cookies.txt Holds
all of your cookies, including login information, session data, and
preferences. permissions.sqlite hostperm.1 Holds preferences about
which sites you allow or prohibit to set cookies, to display images,
to open popup windows and to initiate extensions installation.
Cookie storage depends on both your browser and OS. In older browsers, they were just stored in a file path named something like "Cookies". Most modern browsers store cookies in some encrypted way, usually in a sqllite db flat file. If you could provide more info on what you are trying to track down via the actual local cookie storage (as opposed to using the browser's built in cookie browser), it would help get more info on where to look or alternatives for what you have in mind.
If you want to use persistent cookies with HttpWebRequest, you'll need to import wininet.dll to handle this (or you handle persistence yourself).
There's an example on MSDN in the Community Content section for WebRequest.Create Method.
snippet
[DllImport("wininet.dll", CharSet=CharSet.Auto , SetLastError=true)]
private static extern bool InternetGetCookie (string url, string name, StringBuilder data, ref int dataSize);
private static string RetrieveIECookiesForUrl(string url)
{
StringBuilder cookieHeader = new StringBuilder(new String(' ', 256), 256);
int datasize = cookieHeader.Length;
if (!InternetGetCookie(url, null, cookieHeader, ref datasize))
{
if (datasize < 0)
return String.Empty;
cookieHeader = new StringBuilder(datasize); // resize with new datasize
InternetGetCookie(url, null, cookieHeader, ref datasize);
}
// result is like this: "KEY=Value; KEY2=what ever"
return cookieHeader.ToString();
}
Related
I'm getting a browser error when using SustainSys.Saml2 library with my app:
400 Bad Request
Request Header Or Cookie Too Large
nginx/1.14.0
I think that reducing my cookie size might help and I only really need the email from the claim data, so I thought that if I could just save the email claim and remove the other claims, that it might reduce my cookie size and fix this error.
I read the response to a similar question (SustainSys.Saml2 Request length header too long) and looked for some information on how to implement AcsCommandResultCreated to remove unused claims (and hopefully reduce cookie size). I didn't find a lot of documentation, but did piece together some ideas and code to try and take a stab at it.
I've tried this code in my global.asax as well as in a controller action (that I made the "returnUrl" after Saml2/Acs). It doesn't look like my FedAuth cookie (set by Saml2/Acs) is any smaller. Any comments or suggestions? Thank you.
// Check if email claim exists
var principal = ClaimsPrincipal.Current;
var userEmail = principal.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Email)?.Value;
// Create new command result that only contains the email claim
if (userEmail != null)
{
var emailClaim = principal.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Email);
Sustainsys.Saml2.Configuration.Options.FromConfiguration.Notifications.AcsCommandResultCreated =
(commandResult, response) =>
{
var newCommandResult = new Sustainsys.Saml2.WebSso.CommandResult();
newCommandResult.Principal.Claims.Append(emailClaim);
commandResult = newCommandResult;
};
}
UPDATE:
It turned out that the test environment that I was using (which used nginx) needed to increase the request header buffer size. Adding these cookies increased the size to around 9500 bytes and nginx by default has a request header buffer size that is lower than that (I think 8000). Contacting the code owners of the test server running nginx, and increasing this solved my problem, without me having to reduce my cookie size.
Do you have a lot of failed authentication attempts? That can leave a lot of Saml2.XYZ correlation cookies around on the domain. Try checking the browser dev tools and clean those up.
The "headers too large" is usually something that happens when a user has tried signing in several times with a failure and those cookies get stuck. The real issue is usually something else - causing the authentication to fail and those correlation cookies to be accumulating.
I am trying to get the path of a cookie
I have several cookies with the same name but with different paths.
The following example return null using the getpath() method
var request = facesContext.getExternalContext().getRequest();
var cookies = request.getCookies();
print(cookies[1].getName()))
print(cookies[1].getPath()))
I also tried the global object "cookie" in xpages but how do I get the path from that?
How can I get the path of all the cookies using ssjs?
You can't. Googled a bit. Seems to be a common problem beyond Domino and XPages. Both getDomain and getPath return null, because browser does not send it to the server. Explained here getDomain() of javax.servlet.http.Cookie is returning null
Also a short thought here https://coderanch.com/t/283519/java/Cookie-getDomain-returns-null that it may be security feature.
Both ways of getting a cookie return a java.servlet.http.Cookie, which does have the getPath() method, which you're using. Are you sure the path is getting set? Looking at an POST request from an XPage (both via the servlet it's calling and FireBug), the DomAuthSessId and SessionID cookies don't have a path set, so getPath() returns null.
I am using Jetty-9 in embedded mode and need only one web application. Consequently I would like the root URL to go to the homepage of that application, i.e. something like
http://localhost:4444/
should end up in a servlet. I start out with:
ServletContextHandler scContext =
new ServletContextHandler(ServletContextHandler.SESSIONS);
scContext.setContextPath("/");
None of the following worked, neither
scContext.addServlet(ListsServlet.class, "/");
nor
scContext.setWelcomeFiles(new String[]{"/lists})
where /lists is mapped to the ListsServlet servlet. All I get is a 403 (Forbidden).
I do not use the DefaultServlet, which seems to handle welcome files. But since the ServletContextHandler has setWelcomeFiles I expected it to contain the logic to use them.
Any ideas?
For the 403 Forbidden error, you have some security setup that is not allowing you to access the handlers/servlets.
Eliminate that security (for now), verify that the rest is working, then add security a bit later to lock down specifics.
If you want to see some the suggestions below at work, consider looking at the code example in the answer from another stackoverflow: How to correctly support html5 <video> sources with jetty.
Welcome files are appended to the incoming request path if there is nothing present at that location. For example requesting a directory and then a welcome-file of 'index.html' is appended to the request path.
While this would work ...
scContext.setWelcomeFiles(new String[]{"lists"})
// Add Default Servlet (must be named "default")
ServletHolder holderDefault = new ServletHolder("default",DefaultServlet.class);
holderDefault.setInitParameter("resourceBase",baseDir.getAbsolutePath());
holderDefault.setInitParameter("dirAllowed","true");
holderDefault.setInitParameter("welcomeServlets","true");
holderDefault.setInitParameter("redirectWelcome","true");
scContext.addServlet(holderDefault,"/");
It's likely not what you are aiming for, as you said the root path only.
The above would also make changes to requests like /foo/ to /foo/lists
Instead, it might make more sense to use a Rewrite rule + handler instead of the welcome-files approach.
RewriteHandler rewrite = new RewriteHandler();
rewrite.setHandler(scContext);
RewritePatternRule rootRule = new RewritePatternRule();
rootRule.setPattern("/");
rootRule.setReplacement("/list");
rootRule.setTerminating(true);
rewrite.addRule(rootRule);
server.setHandler(rewrite);
This RewritePatternRule simply changes any request path / to /list and then forwards that request to the wrapped ssContext (if you want to see the /list on the browser, change it to a RedirectPatternRule instead.
I currently store text to speech mp3 files as varbinary(max) in the database. what I want to do is play those audio files using the embed tag where the source is ashx file that will recieve the id of the database record and write the byte array.
My ashx file has the following code
byte[] byteArray = ttsMessage.MessageContents;
context.Response.Buffer = true;
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.ContentType = "audio/mpeg";
context.Response.OutputStream.Write(byteArray, 0, byteArray.Length);
context.Response.End();
The call from the aspx page is as follows
Panel5.Controls.Add(new LiteralControl(String.Format("<embed src='/TestArea/PreviewWav.ashx?source={0}' type='audio/mpeg' height='60px' width='144px'/>", ttsMessage.Id.ToString())));
I have gotten this to work with the following
Panel5.Controls.Add(new LiteralControl(String.Format("<audio controls='controls' autoplay='autoplay'><source src='/TestArea/PreviewWav.ashx?source={0}' type='audio/x-wav' /></audio>", ttsMessage.Id.ToString())));
Using the audio tag but cannot seem to get it to work with the embed tag.
I am using IE9/VS2010
Any ideas?
I think the wrong thing with embed tag is that...
Embed tag call a plugin like winmediaplayer ocx than handler firstly called from web page than media plugin get the ashx url than it started to call handler.
But web page's request and mediaplayer plugin's requests are diffent so if you check users Authentication or some other header information it fails.
You can easily see that on fiddler utility. On fiddler top-right side shows the request info. there is a user-agent part. Look it carefully.
How many requests happen from your handler,notice them. What are the differs. for each reqs.
If you have this issue,
You may use a ticket system or redirect a safety area for download without header or other request checks. Sadly web page requst cannot complately transfer media player and others.
hope helps
I am looking for a way to handle sessions through cookies in C++. Can anybody please help me with some hints for the solution?
libcurl can help you with this. See "Cookies Without Chocolate Chips" here.
Assuming your C++ code is functioning as a CGI handler, it's merely a matter of reading and writing cookies in the requests and responses.
If your session data is small (less than 32 bytes or so), then you can store it all right in the cookie.
If you need to store more data, or want to share sessions between servers, then you will want to create unique and random IDs to represent your sessions. You should then take that ID and lookup the actual session data (in memory or in a database).
Everything I have written is 1990's CGI 101.
I guess in C++ land, it would look like this:
int main() {
map<string,string> headers = parseRequestHeaders(cin);
int64_t sessionId = 0;
SessionData *session = 0;
if (getSessionId(headers, &sessionId)) {
session = getSession(sessionId);
}
else {
session = newSession();
sessionId = session->id();
setCookie(sessionId);
}
// ...
}