i used following code to get the access token from code as below
String code = HttpContext.Current.Request["code"];
string redirecturl = HttpContext.Current.Request["url"];
string Url = "https://accounts.google.com/o/oauth2/token";
string grant_type = "authorization_code";
string redirect_uri_encode = UrlEncodeForGoogle(url);
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}&access_type={5}";
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
string param = string.Format(data, code,configurationInfo.oauthclientid , configurationInfo.oauthclientsecretid, redirect_uri_encode, grant_type, "offline");
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
i am getting response as
The remote server returned an error: (400) Bad Request.
i do not know where i went wrong
waiting for your valuable comments
Google also provides a higher level library for accessing its services. I find it makes it much easier to work with its APIs.
http://code.google.com/p/google-api-dotnet-client/
Related
I am getting '(400) Bad Request.' when I try complete authenticate against an ALM REST API, the first part (authentication) is successful) and I get the LWSSO_COOKIE_KEY, but site-session always fails with a 400 error code.
What am I doing wrong please... very confused!
// Authentication XML : 0 = User, 1 = Password
private const string AuthenticationXML = #"<alm-authentication>" +
"<user>{0}</user><password>{1}</password></alm-authentication>";
baseRequestURL = settings.QualityCentreURL + "/qcbin/";
Authentication is done first (and is successful) :
string authRequest = baseRequestURL + "authentication-point/alm-authenticate";
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create(authRequest);
string xml = String.Format(AuthenticationXML, qcSettings.Username, qcSettings.Password);
byte[] Requestbytes = Encoding.UTF8.GetBytes(xml);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";
Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();
authenticationCookie = myauthres.Headers.Get("Set-Cookie");
The Site-Session code is :
public void GetSiteSession()
{
// Creat the web request fore site-session.
string request = baseRequestURL + "rest/site-session";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request);
string xml = String.Empty;
byte[] requestbytes = Encoding.UTF8.GetBytes(xml);
// Update the attributes before sending.
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.Accept = "application/xml";
webRequest.Headers.Set(HttpRequestHeader.Cookie, authenticationCookie);
try
{
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(requestbytes, 0, requestbytes.Length);
requestStream.Close();
HttpWebResponse webRequestResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webRequestResponse.GetResponseStream();
XDocument doc = XDocument.Load(responseStream);
}
catch (System.Net.WebException except)
{
Console.WriteLine(except.Message);
}
}
I have tried cutting ;Path=/;HTTPOnly from LWSSO_COOKIE_KEY as per this question, but to no avail.
The API reference I found(here) seems to be a big vague or, possibly that I haven't understood it... :P
Apologies, it seems that with 12.53 I should have been using 'api/authentication/sign-in'
string requestURL = baseRequestURL + "api/authentication/sign-in";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
var credentials = String.Format("{0}:{1}", qcSettings.Username, qcSettings.Password);
request.CookieContainer = authenticationCookieContainer;
request.Headers.Set(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
var authResponse = request.GetResponse();
errorString = String.Empty;
}
catch (System.Net.WebException except)
{
errorString = except.Message;
return false;
}
errorString = String.Empty;
return true;
}
I'm stucked here at getting a WebResponse from HTTPWebRequest.
The WebRequest.GetResponse() Method throws a WebException
("500 Internal Server Error"). When i read the returned HTML it says:
HTTP 403: Forbidden ('_xsrf' argument missing from POST)
Anyone knows this Error or knows what Im doing wrong?
(Im trying to log in to a Website using POST)
EDIT:
My sourcecode:
private String GetLoginCookies(String pHTTPurl, String pUserIDwithFormID, String pPasswordWithFormID)
{
String loginPageUrl = pHTTPurl;
CookieContainer cookieContainer = new CookieContainer();
var Request = (HttpWebRequest)WebRequest.Create(loginPageUrl);
Request.CookieContainer = cookieContainer;
Request.Method = "GET";
WebResponse Response = Request.GetResponse();
HttpWebResponse HttpResponse = Response as HttpWebResponse;
CookieCollection cookies = null;
if (HttpResponse != null)
{
//Cookies die benötigt werden um den Loginvorgang abzuschließen
cookies = HttpResponse.Cookies;
}
string formParams = string.Format(pUserIDwithFormID + "&" + pPasswordWithFormID);
Request = (HttpWebRequest)WebRequest.Create(loginPageUrl);
Request.CookieContainer = cookieContainer;
Request.UserAgent = "I am not a Bot! Ok maybe..";
WebResponse resp = null;
Request.ContentType = "application/x-www-form-urlencoded";
Request.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
Request.ContentLength = bytes.Length;
using (Stream os = Request.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
try
{
resp = Request.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
String TestResponse = sr.ReadToEnd();
}
}
catch (WebException WE)
{
DebugConsole.AppendText("HTTP Error:" + WE.Message + Environment.NewLine);
String HTML = new StreamReader(WE.Response.GetResponseStream()).ReadToEnd();
DebugConsole.AppendText(HTML);
return null;
}
String cookieHeader = resp.Headers["Set-cookie"];
if (String.IsNullOrEmpty(cookieHeader))
return null;
else
return cookieHeader;
}
This is actually because the web method requires anti csrf (cross site request forgery, more info here: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) validation parameter. What you can do, is to append the csrf value to the request header:
postHeaders.Add("X-CSRFToken", CSRF);
Maybe you can paste your source code here if you need any help with that, so we can look after it
OK! Solution found!
After getting the response of the Log-In site, search in the "Set-cookie" Header for _xsrf. This is the Token you have to put in the header of the next POST request.
I have rest api url like this
https://example.com/ProductAPI/api/V1/getproduct.
This api has api_key,username and password.How can I access this api and getproduct details using c#.I tried like this
WebRequest request = WebRequest.Create(#"https://example.com/ProductAPI/api/V1/getproduct");
request.Method = "GET";
request.Headers.Add("api_key","5g13441f-6915-4a34-8a53-bcb4er88b554");
request.Headers["Authorization"] = "Basic" + Convert.ToBase64String(Encoding.Default.GetBytes("admin:123"));
request.ContentLength = 0;
request.ContentType = #"application/json; charset=utf-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
jsonResponse = sr.ReadToEnd();
Console.WriteLine(jsonResponse);
Console.ReadLine();
}
But it show 401 unauthorized error.Pls help to solve this
I am facing trouble in making an HTTP post request to Paypal for Secure token to use Paypal's Hosted solution but I am getting this error:
Some required information is missing or incorrect. Please correct the fields below and try again.
Error: Invalid Merchant or Merchant doesn't exist!
This is my C# code throught which I am making HTTP calls:
string strNVP = "https://pilot-payflowpro.paypal.com?PARTNER=PayPal&USER=myUsername&VENDOR=myVendorName&PWD=myPassword&TRXTYPE=A&AMT=" + obj.CurrentPackagePrice + "&CREATESECURETOKEN=Y&SECURETOKENID=" + Guid.NewGuid().ToString("N");
HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVP);
wrWebRequest.Method = "POST";
StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
requestWriter.Write(strNVP);
requestWriter.Close();
HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());
//and read the response
string responseData = responseReader.ReadToEnd();
responseReader.Close();
string result = Server.UrlDecode(responseData);
string[] arrResult = result.Split('&');
Hashtable htResponse = new Hashtable();
string[] responseItemArray;
foreach (string responseItem in arrResult)
{
responseItemArray = responseItem.Split('=');
htResponse.Add(responseItemArray[0], responseItemArray[1]);
}
string responseResult = htResponse["RESULT"].ToString();
string response = htResponse["RESPMSG"].ToString();
///for Success response
if (responseResult == "0" && response == "Approved")
{
ViewBag.secureToken = htResponse["SECURETOKEN"].ToString();
ViewBag.secureTokenId = htResponse["SECURETOKENID"].ToString();
}
Kindly help me in this problem may b I have done some wrong in my code above also.
The issue was that I was unable to receive a Token and TokenID due to that this exception was arising and then I resolved my issue by making modifications in the above code so that the Paypal sends back a response with Token and TokenID which I used in iframe and its working perfect now.
var request = (HttpWebRequest)WebRequest.Create("https://pilot-payflowpro.paypal.com");
var postData = "PARTNER=PayPal&USER=myUser&VENDOR=myVendor&PWD=myPassword&TRXTYPE=A&AMT=50&CREATESECURETOKEN=Y&SECURETOKENID=" + Guid.NewGuid().ToString("N");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var responseData = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(responseData.GetResponseStream()).ReadToEnd();
string result = Server.UrlDecode(responseString);
string[] arrResult = result.Split('&');
Hashtable htResponse = new Hashtable();
string[] responseItemArray;
foreach (string responseItem in arrResult)
{
responseItemArray = responseItem.Split('=');
htResponse.Add(responseItemArray[0], responseItemArray[1]);
}
string responseResult = htResponse["RESULT"].ToString();
string response = htResponse["RESPMSG"].ToString();
///for Success response
if (responseResult == "0" && response == "Approved")
{
ViewBag.secureToken = htResponse["SECURETOKEN"].ToString();
ViewBag.secureTokenId = htResponse["SECURETOKENID"].ToString();
}
The above code is buggy and throws exceptions while receiving a response etc. So this code block is working good.
I'm trying to get html code of authorizated steam page, but I can't log in.
My code is
public string tryLogin(string EXP, string MOD, string TIME)
{
var rsa = new RSA();
string encryptedPass;
rsa.Exponent = EXP;
rsa.Modulus = MOD;
encryptedPass = rsa.Encrypt(Pass);
string reqString = "username=kasyjack&password=" + encryptedPass + "&emailauth=&kasyjackfriendlyname=&captchagid=&captcha_text=&emailsteamid=&rsatimestamp=" + TIME + "&remember_login=false";
byte[] requestData = Encoding.UTF8.GetBytes(reqString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://store.steampowered.com/login/dologin/");
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.ContentLength = requestData.Length;
request.Host = "store.steampowered.com";
request.Method = "POST";
request.UserAgent = Http.ChromeUserAgent();
request.CookieContainer = _CookieCont;
using (Stream st = request.GetRequestStream())
st.Write(requestData, 0, requestData.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string RSAR = sr.ReadToEnd();
return RSAR;
}
but response message is
{"success":false,"requires_twofactor":false,"clear_password_field":true,"captcha_needed":false,"captcha_gid":-1,"message":"Incorrect login."}
So does anyone know, what's wrong with login? Need your help.
SteamBot repository on GitHub has a working example on how to login to Steam via their website: link to method.
Here is a diagram explaining the whole process(made by me):