Difficulties with google authentication - c#

I am trying to authenticate google with the following code but google sent me back to the login page again.
//STEP# 1
string loginURL = "https://www.google.com/accounts/ServiceLoginBox?service=analytics&nui=1&hl=en-US&continue=https%3A%2F%2Fwww.google.com%2Fanalytics%2Fsettings%2F%3Fet%3Dreset%26hl%3Den%26et%3Dreset%26hl%3Den-US";
request = (HttpWebRequest)WebRequest.Create(loginURL);
request.CookieContainer = cookieJar;
request.Method = "GET";
request.KeepAlive = true;
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008111217 Fedora/3.0.4-1.fc10 Firefox/3.0.4";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
foreach (Cookie cook in response.Cookies)
{
cookieJar.Add(cook);
}
using (StreamReader sr = new StreamReader(response.GetResponseStream()) )
{
serverResponse = sr.ReadToEnd();
sr.Close();
}
galx = ExtractValue(serverResponse,"GALX","name=\"GALX\" value=\"");
Console.WriteLine(galx);
//Request# 2
string uriWithData = "https://www.google.com/accounts/ServiceLoginBoxAuth";
request = (HttpWebRequest)WebRequest.Create(uriWithData);
request.KeepAlive = true;
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008111217 Fedora/3.0.4-1.fc10 Firefox/3.0.4";
request.Method = "POST";
request.CookieContainer = cookieJar;
string param = string.Format("Email={0}&Passwd={1}&continue={2}&service=analytics&nui=1&dsh=8209101995200094904&GALX={3}&hl=en-US&PersistentCookie=yes","**my email address**",p,"",galx);
byte[] postArr = StrToByteArray(param);
request.ContentType = #"application/x-www-form-urlencoded";
request.ContentLength = param.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(postArr,0,postArr.Length);
reqStream.Close();
response = (HttpWebResponse)request.GetResponse();
foreach (Cookie cook in response.Cookies)
{
cookieJar.Add(cook);
}
using (StreamReader sr = new StreamReader(response.GetResponseStream()) )
{
serverResponse = sr.ReadToEnd();
Console.WriteLine(serverResponse);
// Close and clean up the StreamReader
sr.Close();
}

I have no idea an I am pretty sure not many people are going to want to sift through that much code.
One thing that I see at a glance that may be causing problems is that you are playing with the cookies too much.
Create one CookieContainer and just pass it in with each request.
No need to 'transfer' or 'recreate' the container.

Try looking into google accounts api and GBaseService. I believe you will have to set HOSTED_OR_GOOGLE in accountType as Marty has done here in this post.

Related

HttpWebRequest only send Get requests and not post

im trying to send POST request using HttpWebRequest and fiddler shows me that im sending GET?
any help will be appreciated since im able to see what im doing wrong.
code :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(LOGIN_API_BASE_URL);
string postString = string.Format("api_email={0}&api_password={1}", EMAIL, PASSWORD);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postString);
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;
//request.AllowWriteStreamBuffering = true;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.Timeout = i_timeout;
//request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";
//request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
//request.Referer = "https://accounts.craigslist.org";
using (Stream writer = request.GetRequestStream())
{
writer.Write(data, 0, data.Length);
//writer.Close();
}
StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
request.GetResponse().Close();
ok found the problem, the url im sending the request to is http://domain.com and when i send it to http://www.domain.com it works and send a post. so new question why is that? ( the answer will get the answer to my question as i dont like the idea of voting my self )

HttpWebrequests facebook login and request app token

I'm trying to login on facebook and retrive a token by using this link:
https://www.facebook.com/dialog/oauth?client_id=282892925078054&redirect_uri=https://www.facebook.com/&response_type=token
My code looks like this, but i get an invalid link when i'm requesting the link above.
CookieCollection cookies = new CookieCollection();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.facebook.com/login.php?login_attempt=1");
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
//Get the response from the server and save the cookies from the first request..
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies = response.Cookies;
string getUrl = "https://www.facebook.com/login.php?login_attempt=1";
string postData = String.Format("email={0}&pass={1}", email, pass);
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(cookies); //recover cookies First request
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close();
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
cookies = getResponse.Cookies;
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
string sourceCode = sr.ReadToEnd();
}
//Get the token
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://www.facebook.com/dialog/oauth?client_id=282892925078054&redirect_uri=https://www.facebook.com/&response_type=token");
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(cookies);
webRequest.AllowAutoRedirect = false;
HttpWebResponse rresponse = (HttpWebResponse)webRequest.GetResponse();
if (rresponse.StatusCode == HttpStatusCode.Redirect)
{
Console.WriteLine("redirected to: " + rresponse.GetResponseHeader("Location"));
}
Please help me. Thanks in advance.
https://www.facebook.com/dialog/oauth?client_id=282892925078054&redirect_uri=https://www.facebook.com/&response_type=token
The URL does not allow the application configuration.: The application settings do not allow one or more of the URLs. Internet Site URL and Canvas URL or domain URLs must be sub-domains of application domains.

WebClient/HttpRequest Navigating To Page After Login

I want to login to a website using a webclient or httpwebrequest, after i'm logged in i want to navigate to a page in the site.
so i know how to post data and to login, my problem is with the navigation after the login,
it redirect me to the login page, i know it has to do with the cookies, but i dont understand what i'm doing worng... here is my code -> it is taken from another answear on stackoverfllow... (http://stackoverflow.com/questions/8425593/c-sharp-httpwebrequest-post-login-to-facebook)
string getUrl = "somesite.com";
CookieCollection cookies = new CookieCollection();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies = response.Cookies;
string getUrl2 = "somepage.login.com";
string postData = String.Format("username={0}&userpassword={1}", "foo", "foofoo");
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl2);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(cookies);
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
string sourceCode = sr.ReadToEnd();
}
//untill here it works fine i'm logged in....
HttpWebRequest getRequest2 = (HttpWebRequest)WebRequest.Create("a page on the site..");
getRequest2.CookieContainer = new CookieContainer();
getRequest2.CookieContainer.Add(cookies);
HttpWebResponse getResponse2 = (HttpWebResponse)getRequest2.GetResponse();
cookies = getResponse2.Cookies;
using (StreamReader sr = new StreamReader(getResponse2.GetResponseStream()))
{
string sourceCode = sr.ReadToEnd();
}
//here it rediects me to login page
any suggestions> what i'm doing wrong
Do not instantiate CookieContainer for each request. You need one CookieContainer over all requests. Try this:
CookieContainer cc = new CookieContainer();
string getUrl = "somesite.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
request.CookieContainer = cc;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string getUrl2 = "somepage.login.com";
string postData = String.Format("username={0}&userpassword={1}", "foo", "foofoo");
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl2);
getRequest.CookieContainer = cc;
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
string sourceCode = sr.ReadToEnd();
}
//untill here it works fine i'm logged in....
HttpWebRequest getRequest2 = (HttpWebRequest)WebRequest.Create("a page on the site..");
getRequest2.CookieContainer = cc;
HttpWebResponse getResponse2 = (HttpWebResponse)getRequest2.GetResponse();
using (StreamReader sr = new StreamReader(getResponse2.GetResponseStream()))
{
string sourceCode = sr.ReadToEnd();
}
//here it rediects me to login page

Send post to java servlet using C# HttpWebRequest

I have task of uploading file to java servlet. I installed Fiddler to see where web requests are sent and what post data is sent. After logging into java servlet using HttpWebRequest GET method I receive in cookies SessionId. So I was using this SessionId in headers to create POST request to the web server where servlet is. But in response I receive message that "session is time out. Try to login again." But if I use application through user interface I have the one SessionId for all application which is sent in headers with each request.
This application is running in bank so I was thinking if they have some security against scraping.
Am I thinking in a right way? Any help will be appreciated.
Thanks, Elena
Here is my code
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://go.tkygw.pcnet.smbc.local/MgbTokyoGateway/Mgblinkmenu.aspx");
req.Credentials = new NetworkCredential("GB54326", "elena83", "TKYGW");
req.CookieContainer = cookieContainer;
req.Headers.Add("Pragma", "no-cache");
req.Headers.Add("Accept-Language", "en-gb");
req.ProtocolVersion = HttpVersion.Version10;
req.AllowAutoRedirect = true;
WebResponse resp = req.GetResponse();
//here in cookies I receive ASP.NET_session_Id and tkygw_intra
HttpWebResponse webr = (HttpWebResponse)resp;
StreamReader r = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8);
string res = r.ReadToEnd();
resp.Close();
NameValueCollection nvc = new NameValueCollection();
nvc.Add("_PAGEID", "MWMAL1000P00");
nvc.Add("_SENDTS", "1296208904759");
nvc.Add("_TRANID", "AL1000T00P01");
nvc.Add("_SUBINDEX", "-1");
nvc.Add("_TARGET", "");
nvc.Add("_FRAMID", "");
nvc.Add("_LUID", "1296208904720");
nvc.Add("_WINID", "root");
nvc.Add("_TARGETWINID", "TIMEOUTW_300000_13");
nvc.Add("CHK_FLG", "0");
nvc.Add("BUTTON_NAME", "Corporate Card");
nvc.Add("TITLE_NAME", "[AL1000]Main Menu");
nvc.Add("DateFormat", "1");
nvc.Add("BIZKEY", "AC");
nvc.Add("H_REG_NUM", "");
nvc.Add("H_TODO_DISP_MODE", "");
nvc.Add("H_VIEW_CHANGE_FLG", "1");
nvc.Add("H_SMVA_FLG", "0");
nvc.Add("H_SWITCH_ID", "8837");
nvc.Add("T_BOOKING", "8802");
nvc.Add("T_CUSTOMER_ID", "109732");
nvc.Add("P_DATE_FM", "1");
nvc.Add("D_BA_CREDIT_MONITORING_DISABLED", "");
nvc.Add("D_BA_CREDIT_APPLICATION_DISABLED", "");
nvc.Add("D_BA_CREDIT_APPLICATION_DISABLED", "");
nvc.Add("P_BLANKET_APPLI", "");
HttpWebRequest req3 = (HttpWebRequest)WebRequest.Create("http://gcm.tkygw.pcnet.smbc.local/gcmv0/WACSServlet");
//here in cookiesContainer are 4 values: ASP.NET_session_Id , tkygw_intra
req3.CookieContainer = cookieContainer;
req3.Method = "POST";
req3.Accept = "*/*";
// req3.Headers.Add("Pragma", "no-cache");
// req3.Headers.Add("Accept-Language", "en-gb");
req3.AllowAutoRedirect = true;
req3.KeepAlive = true;
req3.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
req3.ContentType = "application/x-www-form-urlencoded";
req3.ProtocolVersion = HttpVersion.Version10;
var sbPostData = new StringBuilder();
if (nvc != null)
{
foreach (string key in nvc.AllKeys)
{
string[] values = nvc.GetValues(key);
if (values != null)
{
foreach (string value in values)
{
if (!string.IsNullOrEmpty(value))
sbPostData.Append(string.Format("{0}={1}&", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value)));
}
}
}
}
var parameterString = Encoding.UTF8.GetBytes(sbPostData.ToString());
req3.Referer = "http://gcm.tkygw.pcnet.smbc.local/gcmv0/WACSServlet?_TRANID=AL0010P01C01";
req3.ContentLength = sbPostData.ToString().Length;
using (Stream requestStream = req3.GetRequestStream())
{
requestStream.Write(parameterString, 0, parameterString.Length);
requestStream.Close();
//nothig is received in cookies. Status of response 200 (OK), but on the web page is error that Session is Time OUT. Please Login again
using (var response = req3.GetResponse() as HttpWebResponse)
{
using (var stIn = new System.IO.StreamReader(response.GetResponseStream()))
{
//here I receive session Time Out. Please login again
string s = stIn.ReadToEnd();
}
}
}
If you are uploading file using HttpWebRequest, you must specify content headers correct.
Content must be specified as Content-Type: multipart/form-data
sample snippet
string DataBoundary = "-----------------------------" + DateTime.Now.Ticks.ToString("x");
string contentType = "multipart/form-data; boundary=" + DataBoundary ;
req.Method = "POST";
req.ContentType = contentType ;
req.UserAgent = userAgent;
req.CookieContainer = new CookieContainer();
req.ContentLength = formData.Length;
Check out this and this posts for more detail explanation

.NET HTTP POST Method - Cookies issue

I'm trying to use C# to login to hotfile.com. The first big issue was to overcome the 417 Error, which this line solved it:
System.Net.ServicePointManager.Expect100Continue = false;
Now I'm getting this error as I try to login using POST:
You don't seem to accept cookies. Cookies are required in order to log in. Help
I've tried several times, and googled around and I still can't login to Hotfile.com.. My code is this:
string response;
byte[] buffer = Encoding.ASCII.GetBytes("user=XX&pass=XX");
CookieContainer cookies = new CookieContainer();
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create("http://hotfile.com/login.php");
WebReq.Credentials = new NetworkCredential("XX", "XX");
WebReq.PreAuthenticate = true;
WebReq.Pipelined = true;
WebReq.CookieContainer = cookies;
WebReq.KeepAlive = true;
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
WebReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1)";
Stream PostData = WebReq.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
response = _Answer.ReadToEnd();
File.WriteAllText("dump.html", response);
Naturally, the user and pass would have your accounts values.
Here's a working example I wrote for you:
var cookies = new CookieContainer();
ServicePointManager.Expect100Continue = false;
var request = (HttpWebRequest)WebRequest.Create("http://www.hotfile.com/login.php");
request.CookieContainer = cookies;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
writer.Write("user=XX&pass=XX&returnto=/");
}
using (var responseStream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
Console.WriteLine(result);
}

Categories