C# CookieContainer not storing cookies from request to response? - c#

I'm sending a request but the cookies are not being stored in my container for the response?
Example of code -
string uri = "https://www.localhost.com/"
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ContentType = "application/x-www-form-urlencoded";
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (Stream stream = request.GetRequestStream())
{
byte[] bytes = new UTF8Encoding().GetBytes(s);
stream.Write(bytes, 0, bytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream2 = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream2, Encoding.UTF8))
{
str6 = reader.ReadToEnd();
}
}
}
as you can see I've implemented
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;
Which should store the cookies from the request within the container for further usage right within the response right? Like if the response needs the request cookies to load the page.

I suggest using HttpClient as it handles cookies for you and is just generally easier to work with. Also note that even though it’s disposable you generally should use the same HttpClient throughout your application. See: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

Related

How do I store a cookie after login

I'm trying to sign in to a website. It should be done by a POST request. But i need to store the cookie somehow.
My actual code:
public void botLogin(string userName, string passWord)
{
ASCIIEncoding encoding = new ASCIIEncoding();
string post_data = "username=" + userName + "&password=" + passWord;
byte[] data = encoding.GetBytes(post_data);
var requestUri = "http://registration.zwinky.com/registration/loginAjax.jhtml";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var sharedCookies = new CookieContainer();
request.CookieContainer = sharedCookies;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
MessageBox.Show(sr.ReadToEnd());
sr.Close();
stream.Close();
}
How would i store the cookie now to use it for other requests?
First of all, cast the created WebRequest to HttpWebRequest. This will give you access to more HTTP-specific properties and methods.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
Define a CookieContainer object at the application level and set that for each created request.
request.CookieContainer = sharedCookies;
I'm pretty sure, the HttpWebRequest object will store the cookies after the download so that the next request can use them. If that still doesn't work, examine the HttpWebResponse object for cookies (again, don't forget to cast the response object to that).

Making WebRequest with OAuth 2.0 in C#

I am trying to make a simple call to a authorization Server with OAuth 2.0.
And I am very new to OAuth 2.0.
How do I make a call to the Authorization Server to get back my access token to send in the request header of request (if I am wording that correctly).
Below is what I have, Thanks in advance to any help.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri);
request.Method = "POST";
var uri = new Uri(Uri);
string postData = output;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
IAuthorizationState authorization = null;
AuthorizationServerDescription serviceDecription = new AuthorizationServerDescription
{
AuthorizationEndpoint = uri,
};
WebServerClient client = new WebServerClient(serviceDecription, Key, Secret);
client.AuthorizeRequest(request, authorization);
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
sr.ReadToEnd();
}
}
else
{
dataStream.Close();
response.Close();
}
}
What AS? how do users authenticate?
Typically, OAuth2 flows require user interaction with a browser (like described in this doc). It'd be great if you could add more context to what you are trying to do.
There are plenty of frameworks that you could use to avoid having to deal with lower level details of OAuth.

Sequence of HttpWebRequest

I am currently in the process of automating a web interface for administrating users of an FTP.
I am trying to do this with HttpWebRequest, i have one call that logs me on the site and the second call is supose to add a new user for the FTP access.
I have tried my two urls in the browser and they work, they end up creating a user.
string login = "https://www.ftpsite.net/./panel/index.php?txvUsername=myaccount&txvPassword=myPassword&submitButton=Login";
this gets me logged in when i enter it in the browser address bar.
the second call to create a user is as follows.
string createUser = "https://www.ftpSite.net/panel/ftpsites/updatelogin?login_id=&login=toto123&realname=realnametoto&homedir=root&passwd=superpassword11&expdate=01-01-2100&neverExpire=on&quota_value=0&quota_unit=GB&group_id=0&status=on&ftp=on&filelist=on&ftp_download=on&http=on&web_filelist=on&web_download=on&email=";
This creates a user when i enter it in the browser's address bar if it follows the one that logs us in.
My problem is that i am trying to do this using HttpWebRequest and without success. I can get myself logged in but when i try to create the user it seems to return a "bad" error code saying i have created too many users already which isnt the case since i can create more after that call. Here is the code i use with HtttpRequest
_datCookie = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(login);
httpWebRequest.Method = "POST";
httpWebRequest.CookieContainer = _datCookie;
WebResponse response = httpWebRequest.GetResponse();
referer = response.ResponseUri.AbsoluteUri;
Stream requestStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(requestStream);
_datCookie = httpWebRequest.CookieContainer;
response.Close();
httpWebRequest = (HttpWebRequest)WebRequest.Create(createUser);
httpWebRequest.CookieContainer = _datCookie;
httpWebRequest.Referer = referer;
httpWebRequest.Method = "POST";
response = httpWebRequest.GetResponse();
requestStream = response.GetResponseStream();
streamReader = new StreamReader(requestStream);
webBrowser.DocumentText = streamReader.ReadToEnd();
response.Close();
What i caught and tried to imitate without success here.
Are you sure they should be POST requests? The URLs seem to have all of the fields in the query-string, which suggests they should be GET requests instead.
Based on the Fiddler screen-shot, you need to make a POST request with the fields in the body, not the query-string:
var cookies = new CookieContainer();
// Request 1 : Login
var request = (HttpWebRequest)WebRequest.Create("https://www.ftpsite.net/./panel/index.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookies;
string postData = "txvUsername=myaccount&txvPassword=myPassword&submitButton=Login";
byte[] postBytes = Encoding.Default.GetBytes(postData);
request.ContentLength = postBytes.Length;
using (Stream bod = request.GetRequestStream())
{
body.Write(postBytes, 0, postBytes.Length);
}
WebResponse response = request.GetResponse();
string referer = response.ResponseUri.AbsoluteUri;
// Request 2 : Create user
request = (HttpWebRequest)WebRequest.Create("https://www.ftpSite.net/panel/ftpsites/updatelogin");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookies;
postData = "login_id=&login=toto123&realname=realnametoto&homedir=root&passwd=superpassword11&expdate=01-01-2100&neverExpire=on&quota_value=0&quota_unit=GB&group_id=0&status=on&ftp=on&filelist=on&ftp_download=on&http=on&web_filelist=on&web_download=on&email=";
postBytes = Encoding.Default.GetBytes(postData);
request.ContentLength = postBytes.Length;
using (Stream bod = request.GetRequestStream())
{
body.Write(postBytes, 0, postBytes.Length);
}
response = request.GetResponse();
requestStream = response.GetResponseStream();
streamReader = new StreamReader(requestStream);
webBrowser.DocumentText = streamReader.ReadToEnd();
response.Close();

using cookies (httpWebRequest,c#)

I read whole answers about httpWebRequest and Cookies in the site, But my problem is still unsolved. I have a winform application that logs into a website (logs correctly) but I can't use it's cookies to still logged in for another pages, I tried many solutions such as using PHPSESSID , using a single CookieContainer in both Requests but none of them was effective.
Here's my code :
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("(Login page)");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.KeepAlive = true;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes("username=uname&password=pass&submit=Button");
webRequest.ContentLength = data.Length;
CookieContainer CookieContainer = new CookieContainer();
webRequest.CookieContainer = CookieContainer;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse webResponse;
webResponse = (HttpWebResponse)webRequest.GetResponse();
HttpWebRequest webRequest1 = (HttpWebRequest)WebRequest.Create("(My control panel page)");
webRequest1.Method = "GET";
webRequest1.KeepAlive = true;
webRequest1.CookieContainer=new CookieContainer();
foreach (Cookie cook in webResponse.Cookies)
{
webRequest1.CookieContainer.Add(cook);
}
webRequest.ContentType = "application/x-www-form-urlencoded";
webResponse = (HttpWebResponse)webRequest1.GetResponse();
string html;
using (Stream strmresponse = webResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(strmresponse, Encoding.UTF8))
{
html = reader.ReadToEnd();
}
}
textBox1.Text = html;
Not sure if you still care, but check the answer to this question out, as it shows how to re-use cookies for multiple requests.

Httpwebrequest not retrieving Cookies

I have created the following code, which as far as Im aware should work fine? It is not receiving any cookies at all, I have double checked with wire shark and the cookies are being returned... this is being developed on Windows Phone 7.
byte[] content = GetLoginRequestContent(username, password);
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(LoginUri);
httpWebRequest.ContentType = AuthContentType;
httpWebRequest.Method = "POST";
httpWebRequest.Headers["referer"] = LoginRequestReferer;
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.Headers[HttpRequestHeader.ContentLength] = content.Length.ToString();
httpWebRequest.BeginGetRequestStream(async1 =>
{
using (Stream stream = httpWebRequest.EndGetRequestStream(async1))
stream.Write(content, 0, content.Length);
httpWebRequest.BeginGetResponse(async2 =>
{
HttpWebResponse rep = (HttpWebResponse)httpWebRequest.EndGetResponse(async2);
CookieCollection cookies = rep.Cookies;
using (Stream stream = rep.GetResponseStream())
using (StreamReader sr = new StreamReader(stream))
{
String contentX = sr.ReadToEnd();
//if blah blah
}
}, null);
}, null);
If the cookie is marked with HttpOnly (which is often the case with session cookies) you cannot access them it client side scripting for security reasons. It is sent to the client, the client resends it to the server (if it posses a cookie container) on subsequent requests, but you cannot read its value on the client.

Categories