I am trying to login to Gmail by posting data.
Here is my code:
HttpWebRequest hi = (HttpWebRequest)HttpWebRequest.Create("https://www.google.com/accounts/ServiceLoginAuth?service=mail");
hi.Method = "POST";
//string PostData = "continue=https%3A%2F%2Fmail.google.com%2Fmail%2F%3Ftab%3Dwm&service=mail&rm=false&dsh=-28214021908461826<mpl=default&scc=1&GALX=6-CDla8snug&pstMsg=1&dnConn=&checkConnection=youtube%3A1271%3A1&checkedDomains=youtube&timeStmp=&secTok=&Email=EMAILADDRESS4u&Passwd=PASSWORD&signIn=Sign+in&rmShown=1";
hi.ContentType = "application/x-www-form-urlencoded";
byte[] post = UnicodeEncoding.UTF8.GetBytes(PostData);
Stream stream = await hi.GetRequestStreamAsync();
stream.Write(post, 0, PostData.Length);
WebResponse response = await hi.GetResponseAsync();
string pageSource;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
mywebview1.NavigateToString(pageSource);
But when I try to run this, I get an error. How can I resolve this issue?
Your browser's cookie functionality is turned off. Please turn it on.
We have already one question related to this...
Have a look..
Using WebRequest cookie in WebBrowser
Use cookies from CookieContainer in WebBrowser
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/00a29544-8cf4-4de2-8e7c-e7931b0e2221
Related
I am developing C# WinForms application to trade on Stex.com.
They upgraded their api to api3.
It uses google authentication app to login.
That's why there's no way to get access token without man's behavior.
Finally, I determined to use postman to get access token and I want to refresh token when the token is expired.
I think it the best way.
So I got the access token and refresh token via postman.
https://help.stex.com/en/articles/2740368-how-to-connect-to-the-stex-api-v3-using-postman .
now it's the turn to refresh my token.
so this is what I wrote.
string refresh_token = "def50200b03974080...";
string client_id = "502";
string client_secret = "SeTs50aFxV1RoMFBW1b4RVNQhh2wEdICaYQrpE3s";
string AccessToken = "eyJ0eXAiOiJKV1QiLCJhbGciO...";
string url = #"https://api3.stex.com/oauth/token";
var request = HttpWebRequest.Create(url);
request.Method = "POST";
request.Headers.Add("Authorization", "Bearer " + AccessToken);
request.ContentType = "application/x-www-form-urlencoded";
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("grant_type", "refresh_token");
outgoingQueryString.Add("refresh_token", refresh_token);
outgoingQueryString.Add("client_id", client_id);
outgoingQueryString.Add("client_secret", client_secret);
outgoingQueryString.Add("scope", "trade profile reports");
outgoingQueryString.Add("redirect_uri", #"https://www.getpostman.com/oauth2/callback");
byte[] postBytes = new ASCIIEncoding().GetBytes(outgoingQueryString.ToString());
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Flush();
postStream.Close();
using (WebResponse response = request.GetResponse())
{
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
dynamic jsonResponseText = streamReader.ReadToEnd();
}
}
It shows 401(Unauthorized) error.
And when I remove ContentType, it shows 400(Bad Request) error.
If anyone did this, please help me.
guys!
Finally, I found the issue.
The issue was due to my ignorance.
Calm down and have a relax when you get issue.
:)
I created 2 api3 clients and so client_secret was different.
Thank you.
I'm trying to write a script in c# capable to retrieve some information from a website. These information are protected so I need to login before I can read them. That's what I think should be my procedure:
First of all use a POST request to login into the website. Here my first problem: the page where I find the login form is this https://idp.kk-abcdefg.com/idp/Authn/UserPassword . Should I submit the POST request to this page or should I use a different address?
I've tested the headers using some tools of Firefox or Chrome but I can't understand which is the right procedure. I have noticed that If I open this login page I receive some cookies. If I delete these cookies and try to login by inserting user and password (via browser) I get an error as a response from the website .. it says that I need to activate cookies to be able to login. So it seems like when I open the login page for the first time I receive some cookies and then I need to send them together with the first POST request for login. Does it make sense for any of you?
That's the code I'm using right now:
string formUrl = "https://idp.kk-abcdefg.de/idp/Authn/UserPassword";
string formParams = string.Format("j_username=MyUserName&j_password=MyPassword”);
string cookieHeader;
string pageSource;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
And I believe this is working because the result of pageSource changes if I use correct user / pass or I write them wrong. But when user / pass are correct, I'm still not able to login because I get the following error message: "This application requires cookies. Please make sure cookies are enabled in the settings of your browser. Please reload the login page and try logging in again".
This is the same error that I get if I disable cookies in my browser or if I delete cookies that I get when I load the login page for the first time.
Can you help me with all that? My idea is that I need to save the cookies received when I open the login page for the first time and then send them together with following requests but I don't know how to do ..
Thanks a lot!
In Web Application, once the user is logged in successfully a cookie is sent back to the browser to track the user session and to determine if the user is logged in or not during further requests. Furthermore login process of your application requires cookies to be sent from client along with username and password. So when you are trying to perform login without browser it complains about missing cookies.
If you know what cookies and their values need to be sent along with username and password for login, you can send them using cookieContainer in WebRequest as following.
string formUrl = "https://idp.kk-abcdefg.de/idp/Authn/UserPassword";
string formParams = string.Format("j_username=MyUserName&j_password=MyPassword");
string cookieHeader;
string pageSource;
CookieContainer cookieContainer = new CookieContainer();
Cookie cookie1 = new Cookie("<<cookiename>>", "<<cookievalue>>","/", "<<yourdomainname>>");
Cookie cookie2 = new Cookie("<<cookiename>>", "<<cookievalue>>", "/", "<<yourdomainname>>");
cookieContainer.Add(cookie1);
cookieContainer.Add(cookie2);
// You can keep adding all required cookies this way.
var req = (HttpWebRequest)WebRequest.Create(formUrl);
req.CookieContainer = cookieContainer;
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
// You can access the cookies coming as part of response as following.
HttpWebResponse response = resp as HttpWebResponse;
if(response != null)
{
var cookiesCollections = response.Cookies;
}
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
If you don't know the cookies and you need to get the cookies first by requesting login page before posting username and password then use following.
var loginPageUrl = "<<Your Login Page url>>";
CookieContainer cookieContainer = new CookieContainer();
var req = (HttpWebRequest)WebRequest.Create(loginPageUrl);
req.CookieContainer = cookieContainer;
req.Method = "GET";
WebResponse resp = req.GetResponse();
HttpWebResponse response = resp as HttpWebResponse;
CookieCollection cookies;
if (response != null)
{
cookies = response.Cookies; //Use this cookies in above code to send with username and password.
}
You send the request login twice and use single CookieContainer object!
private void button1_Click(object sender, EventArgs e)
{
string userName = textBox1.Text;
string password = textBox2.Text;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.youmint.com/LoginVerification.php?name="+userName+"&pass="+password+"&agreement=true&checkvalue=true");
request.Method = "GET";
request.KeepAlive = true;
request.Headers.Add("Keep-Alive: 300");
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
if (responseFromServer.Equals(""))
MessageBox.Show("Successfully logged in!!");
else if (responseFromServer.Equals("1"))
MessageBox.Show("Login failed!");
request = (HttpWebRequest)WebRequest.Create("http://www.youmint.com/FreeSms.html");
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
/*secret code :P */
reader.Close();
dataStream.Close();
response.Close();
}
So, that's my code... The first webrequest logs into the website. It works fine in the browser and returns 1 if the login is not correct. Then the second one is a normal webrequest to a webpage of the same website. But the login is already gone and the response I get is what I get if I'm not logged in! Can someone please tell me what I'm doing wrong? How do I keep it alive? Do I have to use an invisible webbroswer control or something like that?
This has nothing to do with "keep alive".
You need to preserve session cookie between requests. For that you first need to enable cookies for your login request (read HttpWebRequest docs - it is a bit unobvious). Then you need to pass that cookie with all the following reuests.
Also please make use of the using()
#liho1eye is correct. Here's some more info from the HttpWebRequest page:
For security reasons, cookies are
disabled by default. If you want to
use cookies, use the CookieContainer
property to enable cookies.
You'll need to reference the HttpWebResponse.Cookies property to get the initial session token cookie.
Edit:
Here's a quick and dirty sample of making a request to a page, and transferring response cookies to the next request. Didn't do much testing or validation (so beware!) - just to give you the idea of the approach.
//this only has login/password info, you may need other parameters to trigger the appropriate action:
const string Parameters = "Login1$username=pfadmin&Login1$Password=password";
System.Net.HttpWebRequest req = (HttpWebRequest)System.Net.WebRequest.Create("http://[WebApp]/Login.aspx");
req.Method = "GET";
req.CookieContainer = new CookieContainer();
System.Net.HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
//Create POST request and transfer session cookies from initial request
req = (HttpWebRequest)System.Net.WebRequest.Create("http://localhost/AdminWeb/Login.aspx");
req.CookieContainer = new CookieContainer();
foreach (Cookie c in resp.Cookies)
{
req.CookieContainer.Add(c);
}
req.ContentType = "application/x-www-form-urlencoded";
//...continue on with your form POST
I have done this code to login,to retrieve and show a webpage :
// login info array
string postData = "user_name=tler";
postData += "&user_password=lodvader";
byte[] data = Encoding.ASCII.GetBytes(postData);
// web request
WebRequest req = WebRequest.Create("http://www.lol.com/login.php");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
// stream response to string
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream(), Encoding.GetEncoding("iso-8859-1"));
string responseString = reader.ReadToEnd();
// retrieve text within title
Regex rx = new Regex(#"(?<=<title>).+?(?=</title>)");
var variable = rx.Matches(responseString);
// output
Console.WriteLine(variable[0]);
Console.ReadLine();
But, the following page after login is an html redirect like :
<meta http-equiv="refresh" content="3; URL="bb.php">
How to follow this link and retrieve next page ?
Just send a new WebRequest to the bb.php file. Make sure that you use the same CookieContainer since I presume that login.php uses cookie-based sessions to remember you. Check out the HttpWebRequest.CookieContainer property. This requires you to cast your WebRequest to a HttpWebRequest.
Added: (Couldn't write example code in the comment.)
I'm just making code up without proofing now...
var cookies = new CookieContainer();
var firstReq = (HttpWebRequest)WebRequest.Create(".../login.php");
firstReq.CookieContainer = cookies;
var secondReq = (HttpWebRequest)WebRequest.Create(".../bb.php");
secondReq.CookieContainer = cookies
I have found the time to finish it, here the response ( i tried to be as clear as possible ) :
// Cookie for our session
var cookieContainer = new CookieContainer();
// Encode post variables
ASCIIEncoding encoding=new ASCIIEncoding();
byte[] loginDataBytes = encoding.GetBytes("user_name=belaz&user_password=123");
// Prepare our login HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://blabla.fr/verify.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookieContainer;
request.ContentLength = loginDataBytes.Length;
// Write encoded post variable to the stream
Stream newStream = request.GetRequestStream();
newStream.Write(loginDataBytes, 0, loginDataBytes.Length);
newStream.Close();
// Retrieve HttpWebResponse
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Link the response cookie to the domain
cookieContainer.Add(new Uri("http://blabla.fr/"),response.Cookies);
// Prepare our navigate HttpWebRequest, and set his cookie.
HttpWebRequest requestProfile = (HttpWebRequest)WebRequest.Create("http://blabla.fr/bb.php");
requestProfile.CookieContainer = cookieContainer;
// Retrieve HttpWebResponse
HttpWebResponse responseProfile = (HttpWebResponse)requestProfile.GetResponse();
// Retrieve stream response and read it to end
Stream st = responseProfile.GetResponseStream();
StreamReader sr = new StreamReader(st);
string buffer = sr.ReadToEnd();
There is a property of HttpWebRequest called AllowAutoRedirects. Set this to true. Also there is a property called MaximumAutomaticRedirections. Set that to some allowable value to make sure all of them are followed.
You can't do it a easy way, since the meta tag is read by the client and executed.
In this case, when you're using HttpWebRequest, the request doesn't care about the functions the text may have.
So you need to do another request to the page in the URL attribute (bb.php).
-
If the server did the redirection you wouldn't have the problem.
This may be a pathetically simple problem, but I cannot seem to format the post webrequest/response to get data from the Wikipedia API. I have posted my code below if anyone can help me see my problem.
string pgTitle = txtPageTitle.Text;
Uri address = new Uri("http://en.wikipedia.org/w/api.php");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string action = "query";
string query = pgTitle;
StringBuilder data = new StringBuilder();
data.Append("action=" + HttpUtility.UrlEncode(action));
data.Append("&query=" + HttpUtility.UrlEncode(query));
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream.
StreamReader reader = new StreamReader(response.GetResponseStream());
divWikiData.InnerText = reader.ReadToEnd();
}
You might want to try a GET request first because it's a little simpler (you will only need to POST for wikipedia login). For example, try to simulate this request:
http://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Main%20Page
Here's the code:
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Main%20Page");
using (HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse())
{
string ResponseText;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
ResponseText = reader.ReadToEnd();
}
}
Edit: The other problem he was experiencing on the POST request was, The exception is : The remote server returned an error: (417) Expectation failed. It can be solved by setting:
System.Net.ServicePointManager.Expect100Continue = false;
(This is from: HTTP POST Returns Error: 417 "Expectation Failed.")
I'm currently in the final stages of implementing an C# MediaWiki API which allows the easy scripting of most MediaWiki viewing and editing actions.
The main API is here: http://o2platform.googlecode.com/svn/trunk/O2%20-%20All%20Active%20Projects/O2_XRules_Database/_Rules/APIs/OwaspAPI.cs and here is an example of the API in use:
var wiki = new O2MediaWikiAPI("http://www.o2platform.com/api.php");
wiki.login(userName, password);
var page = "Test"; // "Main_Page";
wiki.editPage(page,"Test content2");
var rawWikiText = wiki.raw(page);
var htmlText = wiki.html(page);
return rawWikiText.line().line() + htmlText;
You seem to be pushing the input data on HTTP POST, but it seems you should use HTTP GET.
From the MediaWiki API docs:
The API takes its input through
parameters in the query string. Every
module (and every action=query
submodule) has its own set of
parameters, which is listed in the
documentation and in action=help, and
can be retrieved through
action=paraminfo.
http://www.mediawiki.org/wiki/API:Data_formats