HttpWebRequest cookie for redirected request - c#

In my program I should authorize on the site, get authorization cookie value and send request to page (page1, which url like "mysite.com/lots/8188/request/4261/"), which redirect me to another (page2, which url like "mysite.com/lots/view/8188/"):
sendingRequest.CookieContainer = new CookieContainer();
sendingRequest.CookieContainer.Add(sendingRequest.RequestUri, new Cookie(ASPNETSessionIdCookieName, this.ASPNETSessionIdCookie));
sendingRequest.AllowAutoRedirect = true;
sendingRequest.MaximumAutomaticRedirections = 100;
HttpWebResponse response = (HttpWebResponse)sendingRequest.GetResponse();
Ok, page1 return me expected HTTP 302 Page with expected url of page2, then sendingRequest go to page2, but it don't send ASPNETSessionIdCookieName cookie to page2 and server return me uncorrect response.
How can I use "ASPNETSessionIdCookieName" for redirected request?

The auto-redireciton will follow the cookies domain/URI to check if the cookies should be sent again, once the URL is changing I believe the problem is the first parameter of the CookieContainer.Add.
You're restricting the cookie to the first page URL.
Try change for something like this:
sendingRequest.CookieContainer.Add(new Cookie(ASPNETSessionIdCookieName, this.ASPNETSessionIdCookie));
If you want to restrict the cookie only to that domain you can them use Cookie four parameters constructor.

Related

Pass custom header to two different domains ASP.NET

I'm trying to pass a custom header from one app to another without success, these apps arre hosted on different domains.
Is it posible to do so?
I have this so far.
//App1:
Response.AddHeader("CustomH","Value")
Response.Redirect("differentedomain.com")
//App2:
var customh = Request.Headers["CustomH"]
But on the second domain the request headers are null.
Another thing I tried to do was make a WebRequest to the second app and pass the custom header throug, and It passed Ok, So, then I tried to make a Response.Redirect on the second app but before I set up a session variable
HttpContext.Current.Session["token"] = token;
Response.Redirect(Path.GetFileName(Path), false);
but when I get the final page my session has changed and my session variables has lost.
Is there any way to keep the same session on Response.Redirect????
Regards.
UPDATE
Ok this what i have so far
Domain A
Dim requestUrl As HttpWebRequest = CType(WebRequest.Create(path + "Token.aspx"), HttpWebRequest)
requestUrl.CookieContainer = New CookieContainer()
requestUrl.Headers.Add("tokenHeader", token)
Dim responseUrl As HttpWebResponse = CType(requestUrl.GetResponse(), HttpWebResponse)
For Each cookie As System.Net.Cookie In responseUrl.Cookies
requestUrl.CookieContainer.Add(New Net.Cookie(cookie.Name, cookie.Value, cookie.Domain))
Next
Response.Redirect(url)
As you can see on my first App I Set up my token on the headers and then make a call with the HttpWebRequest
Doamin B
FormsAuthentication.SetAuthCookie(email, false);
After some validations with the token, I Set the Auth Cookie, and then after that I go back to the domain A to Redirect to my final url but when I do that the cookie is emtpy on domain B

CookieContainer returns empty

Hello Everyone i have the follow code
Uri site = new Uri("http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/Cnpjreva_Solicitacao2.asp");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(site);
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;
//Console.WriteLine(cookies.GetCookieHeader(site));
//Get the response and print out the cookies again
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Console.WriteLine(cookies.GetCookieHeader(site));
}
Console.Write("end");
Console.ReadKey();
Well this code returns the Cookie OK but if i change the URI to http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATBHE/ConsultaOptantes.app/ConsultarOpcao.aspx it's not show correctly it's return empty
Anyone can help me to solve this problem ?
The server at the new URL does not attempt to set any cookies, so of course no cookies are in the container. Modify your ASP code to set a cookie and it will work.
Add the following to your cookie: , domain=.receita.fazenda.gov.br. This says that your cookie can be used with any sub-domain of receita.fazenda.gov.br. Have a look at the RFC on cookies or use this Wikipedia article.
UPDATE: Re-reading your OP, there may be a few things that could be going awry.
One thing is that the site is not setting a cookie when making a request for www8.receita.fazenda.gov.br (as mentioned by others). Or, the site did not set the domain field of the cookie sent with the response for the request to www.receita.fazenda.gov.br. I think it's likely the former—the cookie is not being set by the web server when the request is being made.
Another thing is perhaps you forgot to request the cookie header for the correct site?? Above, you have a line of code that reads Console.WriteLine(cookies.GetCookieHeader(site));, where site is hardcoded to a System.Uri that is different from www8.receita.fazenda.gov.br. If that's the case, then you are requesting cookies for a different site than the one for which the request was made.

Get the .ASPXAUTH cookie value programmatically

Is there a way to get the .ASPXAUTH value programmatically.
Example I login to a website with my own credentials (POST) and then read the response...it does not return the .APSXAUTH in the CookieContainer that I use to track the session.
Anyone has a clue how can I get it and send it with the subsequent gets and posts?
[EDIT] Here's what I do to be more specific:
send a HTTP GET to a page. read values like _VIEWSTATE etc.
send a HTTP POST to the Login page. It includes the login information.
The server sends a 302 response (redirect) to some Default page. The forms authentication cookie is supposed to be included but it's not.
So I was thinking that there might be a better way than this to track session:
CookieContainer _cookieJar = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
request.CookieContainer = _cookieJar;
So the summarize the answer:
If you're trying to login programatically on a Forms based authentication website trough your own application make sure you follow the steps you take that track the cookies.
First create a initial GET request, and then do the subsequential POST requests that will do the postback.The request and the responses should be formulated in this way:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
request.CookieContainer = _cookieJar;
HttpWebResponse httpsResponse = (HttpWebResponse)request.GetResponse();
The CookieContainer class handles the cookies as expected.
And if your response is encoded with Gzip just include the following line:
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
before you call request.GetResponse()
Hope this helps someone out there.

How to parse HttpWebResponse.Headers.Keys for a Set-Cookie session id returned

I'm trying to create an HttpWebRequest/HttpWebResponse session with an ASP.NET website to later parse an HTML form through url params (this part I know how to do), but I do not understand how to parse and set a cookie such as the session id. In Fiddler, it shows that the ASP.NET Session ID is returned through Set-Cookie in the response to the request to the / path of the url, but how can I extract this session id and set it as a cookie for the next HttpWebRequest? I understand that this Set-Cookie header would be found in HttpWebResponse.Headers.Keys, but is there a direct path to parsing it? Thanks!
The .NET framework will manage cookies for you. You don't have to concern yourself with parsing the cookie information out of the headers or adding a cookie header to your requests.
To store and send your session ID, use the Cookie and CookieContainer classes to store them and then make sure you send your cookies with every request.
The following example shows how to do this. The CookieContainer, 'cookieJar' can be shared across multiple domains and requests. Once you add it to a request object, the reference to it will also be added to the response object when the response is returned.
CookieContainer cookieJar = new CookieContainer();
var request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
request.CookieContainer = cookieJar;
var response = request.GetResponse();
foreach (Cookie c in cookieJar.GetCookies(request.RequestUri))
{
Console.WriteLine("Cookie['" + c.Name + "']: " + c.Value);
}
The output of this code will be:
Cookie['PREF']: ID=59e9a22a8cac2435:TM=1246226400:LM=1246226400:S=tvWTnbBhK4N7Tlpu
The answer from Dan Herbert helped me really. I appreciate your help.
Just want to post my usage - hope it helps some one at some point of time. My requirement is that I need to send back cookies from first http post response to second http post request.
1st:
CookieContainer cookieJar = new CookieContainer();
request.CookieContainer = cookieJar;
....
CookieCollection setCookies = cookieJar.GetCookies(request.RequestUri);
2nd:
CookieContainer cc = new CookieContainer();
cc.Add(setCookies);
request.CookieContainer = cc;
I have the same problem (with amazon)
I use the following regexp:
string regexp = "(?<name>[^=]+)=(?<val>[^;]+)[^,]+,?";);MatchCollection myMatchCollection = Regex.Matches(cookiesStr, regexp);foreach (Match myMatch in myMatchCollection) { string cookieName = myMatch.Groups["name"].ToString(); string cookieVal = myMatch.Groups["val"].ToString(); Cookie cookie = new Cookie(cookieName, cookieVal); cookies.Add(cookie); }
Note that I only care about the cookie name/value...
good luck
Elia
hum I may be wrong but from what I am observing lately
Cookies from a first response, don't include the 'set cookie' as cookies that come in the header (for example some session id...) in the case of a 302 (redirect) status
If the autofollowredirect is set to true, then the set cookie are processed, and the subsequent request which is done automatically, will include those cookies defined by set cookie on the first call
If autofollowredirect is set to false then the first request doesn't get the cookies positionned by the set cookie, and I guess and this is also my queston if anyone know, that the only way to subsequently have those cookies in next request, is parse the set cookies ?

HTTPS C# Post?

I am trying to login to a HTTPS website and then navigate to download a report using c# (its an xml report) ?
I have managed to login OK via cookies/headers etc - but whenever I navigate to the link once logged in, my connection takes me to the "logged out" page ?
Anyone know what would cause this ?
Make sure the CookieContainer you use for your login is the same one you use when downloading the actual report.
var cookies = new CookieContainer();
var wr1 = (HttpWebRequest) HttpWebRequest.Create(url1);
wr1.CookieContainer = cookies;
// do login here with wr1
var wr2 = (HttpWebRequest) HttpWebRequest.Create(url2);
wr2.CookieContainer = cookies;
// get the report with wr2
It can be any number of reasons. Did you pass in the cookie to the download request? Did you pass a referrer URL?
The best way to check is to record a working HTTP request with Wireshark or any number of Firefox extensions or Fiddler.
Then try to recreate the request in C#

Categories