AWS 400 Bad Request error C# - c#

I am tasked with developing an application that Posts data to the client's Amazon Web Service api. The instructions from client were that I have to use the POST method for URL http://ec.*******.compute.amazonaws.com/api and gave me a token to use for authentication.
My C# code looks like this
SystemSettings _Settings = GetSystemSettings(); //URL and Token values
try
{
JObject jsonObject = GetJsonData();
WebRequest request = HttpWebRequest.Create(_Settings.HttpService);
if (!string.IsNullOrEmpty(_Settings.BearerToken))
{
request.PreAuthenticate = true;
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + _Settings.BearerToken);
}
//Uploading JSON
request.ContentType = "application/json; charset=utf-8";
//using Http POST Method
request.Method = "POST";
//Start uploading data
StreamWriter httpStream = new StreamWriter(request.GetRequestStream());
httpStream.Write(jsonObject.ToString());
httpStream.Close(); // Close stream
httpStream.Dispose(); //Dispose stream
//Check for response from the web server
WebResponse response = request.GetResponse(); //Error comes here
.
.
.
.
}
catch(Exception ex)
{
_log.Error("ERROR Uploading to stream(" + _Settings.HttpService + ")", ex);
}
The request ends up with a 400 Bad Request. Does this require working with Amazon SDK to connect to use the Bearer Token?
The customer has said the following:
Our API Authentication is RFC6750, Can you please make a request to
the API as follows:
POST /api/ HTTP/1.1
Host: ec.************.compute.amazonaws.com
Authorization: Bearer ***TOKEN***

Related

The remote server returned an error: (401) Unauthorized c#

i am doing one project which will connect to some broker.. it will send a request and get response from server. I need to handle 2 request. one is authentication request and second is approve request. My authentication request is working fine but my approve request is failing with "unauthorized" error. Can someone please guide me whats going wrong. There API says we need to send all data in header with GET as method.Thats the reason I have added as custom headers. Help will be highly appreciated.
HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(www.someurl.com);
webrequest.Headers.Add("Machine", Dns.GetHostName());
webrequest.Headers.Add("Authorization", "bearer" + LoginToken); //This token I get during authentication. i also tried removing the word "bearer" still it is failure.
webrequest.Headers.Add("username", requestList[0].userid);
webrequest.Headers.Add("messageType", "SS");
webrequest.Headers.Add("customerUniqueTransactionId", requestList[0].locateId);
webrequest.Headers.Add("scageUserId", requestList[0].userid);
webrequest.Headers.Add("accountNumber", requestList[0].account);
webrequest.Headers.Add("security", requestList[0].symbol);
webrequest.Headers.Add("currencyId", "024");
webrequest.Headers.Add("orderQuantity", requestList[0].shares.ToString());
webrequest.Headers.Add("tifInd", "IOC");
webrequest.Headers.Add("repCodeId", "1980");
webrequest.Headers.Add("overrideException", "N");
webrequest.Accept = "application/json";
webrequest.ContentType = "application/json";
**webrequest.Method = "GET";**
HttpWebResponse resp = (HttpWebResponse)webrequest.GetResponse();
Stream oRespStrm = resp.GetResponseStream();
using (StreamReader oStrmRead = new StreamReader(oRespStrm))
{
responseFromServer = oStrmRead.ReadToEnd();
}

getting access tokens forbidden 403 and some times 400 Bad Request

I am facing the following issue while issuing request to retrieve the access token. First, I registered the application in developer console and consequently downloaded the client secret file. The content of which is as below: (i have marked secrets as xxxxx).
{"installed":{"client_id":"xxxx","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"xxxx","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
In the developer documentation (located at : https://developers.google.com/identity/protocols/OAuth2InstalledApp ) however, it is given a different address to connect and retrieve the access tokens.
POST /oauth2/v3/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
I am confused
1. which URI's to use to get access to tokens.
2. What redirect_uri should be used? Is it the local host or the uri as noted in the developer documentation.
When i use the client secret token uri, i receive a 400 bad request and when i use the uri as noted in the developer documentation, I receive forbidden 403.
POST /oauth2/v3/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
Can someone kindly clarify. It would be an immense help.
I am writing a console application and i do not want to use the C# api already provided. The sample code is located below.
Where am I doing wrong?
string tokenUri = #"https://accounts.google.com/o/oauth2/token";
HttpWebRequest request=(HttpWebRequest) WebRequest.Create(tokenUri);
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("code", this.clientCode);
outgoingQueryString.Add("client_id", this.clientID);
outgoingQueryString.Add("client_secret", this.clientSecret);
outgoingQueryString.Add("redirect_uri", "https://oauth2-login-demo.appspot.com/code");
outgoingQueryString.Add("grant_type","authorization_code");
string postdata = outgoingQueryString.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postdata);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream reqStr = request.GetRequestStream();
reqStr.Write(byteArray, 0, byteArray.Length);
reqStr.Flush();
reqStr.Close();
HttpWebResponse response=request.GetResponse() as HttpWebResponse;
Console.WriteLine(response.StatusCode.ToString());
Found out that url-encoded is not to be used, instead json is expected. revised the code as below and still 400 persist.
string tokenUri = "https://accounts.google.com/o/oauth2/token";
TokenFileds f = new TokenFileds() { client_code = this.clientCode, client_id = this.clientID, client_secret = this.clientSecret, redirect_uri = "urn:ietf:wg:oauth:2.0:oob", grant_type = "authorization_code" };
//string retString=this.SerializeToJson<TokenFileds>(f);
string retString = this.NewjsonLib(f);
byte[] byteArray=Encoding.UTF8.GetBytes(retString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(tokenUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
request.ContentLength = byteArray.Length;
Stream strm = request.GetRequestStream();
strm.Write(byteArray, 0, byteArray.Length);
strm.Flush();
strm.Close();
HttpWebResponse response =request.GetResponse() as HttpWebResponse;
you need to insure few things before as,
1. While creating the project you have to select other type project.
2. You must enable the drive API's.
3. Then make sure you are posting this url L"/o/oauth2/token" to this server L"accounts.google.com".
4. you are giving Content Type as L"Content-Type: application/x-www-form-urlencoded".
5.and your header should be like this,
wstring wstrHeader = L"code="+ m_wstrAuthCode +
L"&client_id=327293200239-4n4a8ej3jlm1fdufqu7httclg5a28m1a.apps.googleusercontent.com&client_secret=ieEGhWhPhotp0ZegdgRLkOxv&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code";
here you have to replace m_wstrAuthCode to your authentication code.
6.then you will get the Json from server as,
{
"access_token" : "ya29.7gGjEgvIVIMOO7bHegijk2KygAVjjxz7bCOxUvG7OKeKTc66Nom1e9zCqSyzR4V0bTYC",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "1/Vc9A7nfib4ikeYs0-TBfrs-isvjRDt-JI2ftj0pNVcRIgOrJDtdun6zK6XiATCKT"
}
7.you need to parse it to get the access token.

SurveyMonkey API - Authorization Token Not Found

I built a C# application about 8 months ago to pull SurveyMonkey responses and store them on our SQL Server. The application has run every day for over 6 months without any issue, but suddenly Friday morning I can't get any requests to go through. I'm not seeing anything on the developer site mentioning outages, so I've been examining my code for possible issues.
This is the first app I've ever written to create web requests, so it's possible I'm doing things badly.
Request, from Fiddler:
POST https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=<key hidden> HTTP/1.1
Authorization: bearer <token hidden>
Content-Type: application/json
Host: api.surveymonkey.net
Content-Length: 146
Expect: 100-continue
Connection: Keep-Alive
{
"page": 1,
"fields": ["title","analysis_url","preview_url","date_created","date_modified","language_id","question_count","num_responses"]
}
Response body, from Fiddler:
{"status":1,"errmsg":"Request header \"Authorization\" token not found"}
C# code:
private JObject SubmitPostRequest(string URIPath, string RequestBody)
{
using (var webClient = new WebClient())
{
// Create URI for POST request to go to. URI varies depending on API method and includes API Key.
Uri requestURI = new Uri(APIHost, URIPath + "?api_key=" + APIKey);
// Have web client use NT credentials for proxy server
webClient.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
// Specify headers: access token in authorization header, content type
webClient.Headers["Authorization"] = "bearer " + AccessToken;
webClient.Headers["Content-Type"] = "application/json";
// Create requestBody as byte[]
byte[] requestBody = Encoding.Default.GetBytes(RequestBody);
// Connect to the URI and send requestBody as a POST command.
byte[] postResponse = webClient.UploadData(requestURI, "POST", requestBody);
// Update LastConnect
LastConnect = DateTime.Now;
++TransactionCounter;
// Convert byte[] response to string, parse string and return as JObject.
JObject jsonResponse = JObject.Parse(Encoding.Default.GetString(postResponse));
// Evaluate "status" field of jsonResponse. Throw exception if response is not 0.
dynamic dyn = jsonResponse;
if (dyn.status != 0)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("HTTP Post request failed:");
sb.Append("\tstatus: ").AppendLine(dyn.status.ToString());
sb.Append("\terrmsg: ").AppendLine(dyn.errmsg.ToString());
throw new WebException(sb.ToString());
}
return jsonResponse;
}
}
It took awhile, but I managed to get in touch with someone in corporate IT who monitored the traffic to see what was going on. They implemented a fix to the proxy server and everything is finally working again.

Passing login info when sending HttpRequest to SFDC Web Service

Trying to send JSON HttpRequest to SFDC Web Service, get following response:
[1]
0: {
message: "Session expired or invalid"
errorCode: "INVALID_SESSION_ID"
}
How correctly pass session id or another information from LoginResult with HttpRequest? Code sample follows:
// Generate JSON
MyClass object = new MyClass();
string post_data = JsonSerializer.SerializeToString(object); // this is what we are sending
// this is where we will send it
string uri = "https://url.salesforce.com/some_path/";
// create a request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.Method = "POST";
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
request.ContentType = "application/json";
request.ContentLength = postBytes.Length;
// Setup proxy and SFDC login
LoginResult result = SfdcConnection.GetLoginResult();
// ------------ Need to add login info here -----------------
// now send it
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
// grab te response and print it out to the console along with the status code
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string jsonResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
You need to pass the sessionId in the Authorization header, using the oauth pattern, so it'd be
request.Headers.Add("Authorization", "Bearer " + result.sessionId);
The sessionId is usable for quite some time, so just call login once, not before each REST api call.
This covered in more detail in the REST API docs.
You need to attach the LoginResult (which most likely contains the session ID) to your request, otherwise, the web service just sees a request with no session ID (and no cookies either), and has no way of verifying that you are the client that logged in.
pseudocode
LoginResult result = SfdcConnection.GetLoginResult();
// attach sesionId to your request, see the web services documentation for this
request.Headers.Add("sessionId", result.sessionId);

Instagram oAuth login fails with 403 Forbidden error using C# desktop app

I am developing my Instagram desktop app and I can't authorize user because of 403 Forbidden error.
I am stuck in getting the response from the login POST-request. My POST-string looks like so:
csrfmiddlewaretoken=98d25eec9c3d1a6935e5a491ff2fa543&username=myname&password=mypassword
and this is how i am forming my request:
Uri url = new Uri
("https://instagram.com/accounts/login/?next=/oauth/authorize/?client_id=" +
instagramClient_id + "&redirect_uri=" + instagramRedirectUrl +
"&response_type=token");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cc;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
byte[] sentData = Encoding.UTF8.GetBytes(data);
request.ContentLength = sentData.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(sentData, 0, sentData.Length);
}
WebResponse response = request.GetResponse();
The result is - 403 Forbidden. Can't find out what am i doing wrong.
I can't help mentioning the fact that I have tested some other ways to complete the authorization and noticed that Google Chrome recieves much more cookies then C# request when working with Instagram. So far my desktop app doesn't receive a "sessionid", "__qca", "__utma", "__utmb", "__utmc", "__utmz", "ccode" and "user_segment" cookies. But it recieves "csrftoken" and "mid" cookies. Maybe that's why i'am always having a 403 error?
Add Referer header with the value of the request URL.

Categories