Auto login by using HttpWebRequest - httpwebrequest

I'm writing a window application by C# to auto login & post topic to a website. I've tried to pass username & password as the method following but the responseText did not changed. I meant if I passed the incorrect username or password the responseText would be included the "Error text such: wrong password or username" or if I passed to right username & password the responseText would be included "Login successfully" but the responseText I received was like a original login page
Do you have any idea? Thank you so much
private string Login()
{
HttpWebRequest request;
CookieContainer cookieContainer = new CookieContainer();
string cookieHeader = string.Empty;
byte[] byteArray = Encoding.UTF8.GetBytes("username=abc#gmail.com&password=123");
request = (HttpWebRequest)WebRequest.Create("http://www.vietnamworks.com/dang-nhap");
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = userAgent;
request.Method = "POST";
request.CookieContainer = cookieContainer;
request.ContentLength = byteArray.Length;
using (Stream os = request.GetRequestStream())
{
os.Write(byteArray, 0, byteArray.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string pageSource;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
return pageSource;
}

Related

login to aspx page from another site using httprequest

Using C# and ASP.NET I want to programmatically fill login detail on a web page (form) and then 'POST' those values. How do I do this?currently i am using below code but it not work it take me on same page.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://pcs.d2h.com/");
req.Method = "GET";
StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
// extract the viewstate value and build out POST data
string viewState = ExtractViewState(responseData);
string postData =
String.Format(
"__VIEWSTATE={0}&CenterCPH_tbUsername={1}&CenterCPH_tbPassword={2}&CenterCPH_btnSubmit=Login",
viewState, "9115308123", "12345678#A"
);
// have a cookie container ready to receive the forms auth cookie
CookieContainer cookies = new CookieContainer();
HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create("https://pcs.d2h.com/login.aspx");
req2.Method = "POST";
req2.ContentType = "application/x-www-form-urlencoded";
req2.ContentLength = postData.Length;
req2.KeepAlive = true;
req2.CookieContainer = cookies;
req2.AllowAutoRedirect = false;
StreamWriter sout = new StreamWriter(req2.GetRequestStream());
sout.Write(postData);
sout.Flush();
sout.Close();
HttpWebResponse res = (HttpWebResponse)req2.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
HttpWebRequest req3 = (HttpWebRequest)WebRequest.Create("https://pcs.d2h.com/Terminals/Default.aspx");
req3.CookieContainer = cookies;
res = (HttpWebResponse) req3.GetResponse();
sr = new StreamReader(res.GetResponseStream());
returnvalue = sr.ReadToEnd();
sr.Close();
return returnvalue;

Google API HTTP 401 - Token invalid - AuthSub token has wrong scope

I'm struggling with google api for a few days while sending a post request to Google sites API via C# application.
First I redeem the authorization code from google's servers by a GET request:
https://accounts.google.com/o/oauth2/auth?
scope=email%20profile&
state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.mydomain/myHome&
redirect_uri=http://localhost&
response_type=code&
client_id= // CLIENT ID here...
access_type=online&
approval_prompt=auto
In the redirect uri I got the authorization code which I use to claim the
access token:
string RequestUrl;
RequestUrl = "https://www.googleapis.com/oauth2/v3/token";
WebRequest request = WebRequest.Create(RequestUrl);
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "code=4/aPJAhLvlGLxw1fjKDCOpEQjfoVtNDZYq7FzvrziUero#&" +
"client_id=//cilent id here&" +
"client_secret=client secret here&" +
"redirect_uri=http://localhost&" +
"grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
The response containing the token looks like that:
{
"access_token": "ya29.pAGX8f4e0ZyBazzq5rxWVS6lL1jRyj0_GCog5UEO3FiGT2h4cj10jee4ziAoA09vHRoVejN5p7Iw",
"token_type": "Bearer",
"expires_in": 3600,
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjE2NWQ2MzcwZTgzOTI5YmE4Y2E4ZWU5OTMzZTExZjg2Yzg4YzAwNjUifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTA1OTc0NjQwMTUzNzU0NjU1MDE5IiwiYXpwIjoiOTkwMzUxMjA1MzY4LXBudGYxZXNtaXQ3a3Zlbmg5cnRvbW5pMmdhMmY0N2ZsLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJuaXIuazFAaGFpZmFuZXQub3JnLmlsIiwiYXRfaGFzaCI6Imc5MU5wOVRYS2JUaVEzcFpTM2Ewa1EiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXVkIjoiOTkwMzUxMjA1MzY4LXBudGYxZXNtaXQ3a3Zlbmg5cnRvbW5pMmdhMmY0N2ZsLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiaGQiOiJoYWlmYW5ldC5vcmcuaWwiLCJpYXQiOjE0MzU4MjI2ODAsImV4cCI6MTQzNTgyNjI4MH0.CeaQ8S3GG-yeAwqjU1ixdB7ro2SVKp2QdVTXNWl6196oJeQU1LFLpZ9FtrpNEGSDKHXrO5zx0ldE52RYw8TwMKILUqqCHLOewVJQMjZ6tiPzt-b-qeUta6Op4Z9HerwkMK2sofl88G-XZ6jKc7gk1gGPVcATBU7x0-QPRhQxmDUzP7zceVeoOtBD8g7liVHakK9sA5RNonGt-N6SvzECqhSLss7kDuXc4dStnENhyv_9oTIpvVsQplE-cJz7fDHC7mkW7BfwsgKBE8XbruBz5-o3AG5RVGyUTYqDaoq9qr3_NqckiRISUS127scaYwcYPE22Q8L_2AnpfJU0vuxo6g"
}
And the final step is to call the google api using the access_token
this way:
HttpWebRequest req = (HttpWebRequest)System.Net.WebRequest.Create("https://sites.google.com/feeds/site/mydomain");
req.ContentType = "application/atom+xml";
req.Host = "sites.google.com";
req.Method = "POST";
req.Headers["Gdata-version"] = "1.4";
req.Headers["Authorization"] = "Bearer ya29.pAGX8f4e0ZyBazzq5rxWVS6lL1jRyj0_GCog5UEO3FiGT2h4cj10jee4ziAoA09vHRoVejN5p7Iw";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("<entry xmlns='http://www.w3.org/2005/Atom' xmlns:sites='http://schemas.google.com/sites/2008'><title>Source Site</title><summary>A new site to hold memories</summary><sites:theme>slate</sites:theme></entry>");
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
try
{
using (System.Net.WebResponse resp = req.GetResponse())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
string i = sr.ReadToEnd().Trim();
}
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
But at the end of this step I get a 401 http error.
Token invalid - AuthSub token has wrong scope
What am I doing wrong?
Thanks in advance
you are authenticating your users using the following scopes
scope=email%20profile&
The Sites Data API uses the following scope: https://sites.google.com/feeds/.

I got This Error While Implementing Push Notification using REST API::The remote server returned an error: (401) Unauthorized

I got an error While use this code. I give a proper credentials for Urban Airship.
WebRequest request = WebRequest.Create("https://go.urbanairship.com/api/push/");
request.Credentials = new NetworkCredential(UrbanAirShip UserLogin, MasterKey);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
//WRITE JSON DATA TO VARIABLE D
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"]}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
using (Stream dataStream = request.GetRequestStream())
{
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
}
// Get the response.
WebResponse response = request.GetResponse();
//Error "The remote server returned an error: (400) Bad Request"
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
using (Stream dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
using (var reader = new StreamReader(dataStream))
{
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
response.Close();
return true;
}
}
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://go.urbanairship.com/api/push/");
// Set the Method property of the request to POST.
request.Method = "POST";``
// Create POST data and convert it to a byte array.
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\"Device_Token\"]}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
//Do a http basic authentication somehow
string username = "xxxx"; //App Key From Urban Airship
string password = "xxxxx"; //Master Secret Key From Urban Airship
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri("https://go.urbanairship.com/api/push/"), "Basic", new NetworkCredential(username, password));
request.Credentials = mycache;
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();

Could not successfully simulate the form login using c# programming code

Currently I'm trying to simulate the Login using c# code (HttpWebRequest/HttpWebResponse), however I ended up with the login.aspx webpage's html text rather than the html text after successful login.
the returned variable 'html' is exactly the same with the login.aspx webpage itself, seems it did not post the data at all. please help. thank you. dave. here is the code i used
var LOGIN_URL = "http://altech.com.au/login.aspx";
HttpWebRequest webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
StreamReader responseReader = new StreamReader(
webRequest.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
string postData =String.Format(
"ctl00$ContentPlaceHolderBodyMain$txtEmail {0}&ctl00$ContentPlaceHolderBodyMain$txtPassword={1}&btnLogin=Login","myemail", "mypassword");
//have a cookie container ready to receive the forms auth cookie
CookieContainer cookies = new CookieContainer();
// now post to the login form
webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.CookieContainer = cookies;
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.2; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
// write the form values into the request message
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postData);
requestWriter.Close();
HttpWebResponse response2 = (HttpWebResponse)webRequest.GetResponse();
StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.Default);
string html = sr2.ReadToEnd();
You need to URL encode your data or it will not be accepted.
Dictionary<string, string> FormData = new Dictionary<string, string>();
//Add all of your name/value pairs to the dictionary
FormData.Add(
"ctl00$ScriptManager1",
"ctl00$ContentPlaceHolderBodyMain...");
...then to format it correctly...
public string GetUrlEncodedPostData(
Dictionary<string, string> FormData)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < FormData.Count(); ++i)
{
//Better to use string.join, but this is a bit more clear ^_^
builder.AppendFormat(
"{0}={1}&",
WebUtility.UrlEncode(InputNameValue.ElementAt(i).Key),
WebUtility.UrlEncode(InputNameValue.ElementAt(i).Value));
}
//Remove trailing &
builder.Remove(builder.Length - 1, 1);
return builder.ToString();
}

failed to Login to a remote website

I spent too much hours to overcome this, till now with no success
From my site which is developed in MVC im trying to send a login request to a remote site, for example, facebook.
From fiddler It seems that the following inputs are required charset_test, lsd, locale,email, pass.
lsd key seems to be the unique token
Here is my code
CookieContainer cookies = new CookieContainer()
private string GetToken()
{
Uri uri = new Uri("http://www.facebook.com");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.CookieContainer = cookies;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string htmlText = reader.ReadToEnd();
HtmlDocument document = new HtmlDocument(); --> HtmlAgilePack object
document.LoadHtml(htmlText);
//Need to check xpath doesn't return null object
HtmlNode node = document.DocumentNode.SelectNodes("//input[#name='lsd']").First();
return node.Attributes["Value"].Value;
}
private void Login()
{
string postData = string.Format("charset_test=fixcharset_test&lsd={0} &locale=en_US&email=myemail&pass=mypass", HttpUtility.UrlEncode(GetToken()));
Uri uri = new Uri("http://www.facebook.com/login.php");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.CookieContainer = cookies;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
request.Method = "POST";
request.AllowAutoRedirect = true;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
requestWriter.Write(postData);
requestWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
//After login to facebook suppose to
public string void AddFriend()
{
Uri uri = new Uri("http://www.facebook.com");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.CookieContainer = cookies;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string status = response.StatusDescription;
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
return responseDat
}
Keep in mind, that facebook is just an example, Im aware of its API, Im trying to login to site with no API.
sadly, the response return a facebook page with a sorry message for unrecognizing my browser.
Any help will be more than appreciate.
Thanks,
Are you setting HTTP_USER_AGENT on your request?