oauth 2.0 in c# getting 400 error unsure why - c#

i am trying to fetch an access token by calling an API with an auth code and keeping getting a 400 error.
I have read many a web sites and can't see what is wrong with this. thanks. I have left in commented bits as this is other ways I have tried. Appreciate any quick advice
HttpWebRequest request = WebRequest.Create("https://identity.xero.com/connect/token") as HttpWebRequest;
request.Headers.Add("Authorization", "Basic " + b64_id_secret);
//string data = "{ grant_type : refresh_token, refresh_token : " + l_auth_code+ "}";
//string data = "{ 'grant_type' : 'authorization_code', 'code' : '" + l_auth_code + "', 'redirect_uri' : '" + C_XERO_REDIRECT_URL + "'}";
request.ContentType = "application/json";
request.Method = "POST";
//request.ContentType = "application/json";
//request.ContentLength = postBytes.Length;
//request.Accept = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"grant_type\":\"authorization_code\"," +
"\"code\":\"" + l_auth_code + "\","+
"\"redirect_uri\":\"" + C_XERO_REDIRECT_URL + "\"}";
streamWriter.Write(json);
}
// crashes here
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}

Related

JSON Post Request In C#

I am a SQL Developer, JSON and C# are completely new to me. I am trying to get the JSON data from Rest API from elastic DB using POST method. I think my code is incorrect since I am getting all the response from the API even though I am passing string json variable in my c# code.
public static string COSMOS(string getAPiurl, string ApiUserId, string ApiPassword)
{
string url = getAPiurl;
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "POST";
webrequest.ContentType = "application/JSON";
webrequest.Accept = "application/JSON";
String username = ApiUserId;
String password = ApiPassword;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
webrequest.Headers.Add("Authorization", "Basic " + encoded);
using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
{
string json = "{\"query\":{\"bool\":{\"should\":[{\"match\":{\"platform\":{\"query\":\"COSMOS\"}}}],\"filter\":" +
"[{\"range\":{\"cu_ticketLastUpdated_date\":{\"gte\":\"2022-05-01 00:00:00\",\"lt\":" +
"\"2022-05-31 23:59:59\"}}}]}}}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)webrequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var rl = streamReader.ReadToEnd();
httpResponse.Close();
}
I am using the above code in my SSIS script component. When I am trying to debug the above code in the var rl I am getting all the response even though I am passing the filters like "filter":[{"range":{"cu_ticketLastUpdated_date":{"gte":"2022-05-01 00:00:00","lt":"2022-05-31 23:59:59"}}
Please help me with an solution.

Getting System.IO.IOException in mscorlib.dll

i try to make an HTTP POST to an Swagger UI api and wrote this rudimentary Code:
string baseip = "192.168.0.1";
string auth = "authcodre";
string name = "TestMan";
string ip = "1.1.1.1";
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
string URL = "https://" + baseip + ":4444/api/objects/network/host/";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.ContentType = "application/json";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("token:" + auth));
request.PreAuthenticate = true;
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string patchtxt = "{ \"name\": \"" + name + "\", \"_type\": \"network/host\", \"address\": \"" + ip + "\"}";
streamWriter.Write(patchtxt);
streamWriter.Flush();
streamWriter.Close();
Console.WriteLine("Patches");
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); //Einlesen der HTTP-Antwort
string resppatch = reader.ReadToEnd();
Console.WriteLine(resppatch);
Console.ReadLine();
}
It throws me an System.IO.IOException" in mscorlib.dll at this line:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
Can anyone explain why this happens and how to fix it?
Thank you :)

Sending a JSON request to ebay API

Ok so I'm having a bit of trouble getting these JSON requests through to the Ebay API.
Here is the json request:
string jsonInventoryRequest = "{" +
"\"requests\": [";
int commaCount = 1;
foreach (var ep in productsToProcess)
{
jsonInventoryRequest += "{\"offers\": [{" +
"\"availableQuantity\":" + ep.EbayProductStockQuantity + "," +
"\"offerId\":\"" + ep.EbayID.ToString() + "\"," +
"\"price\": {" +
"\"currency\": \"AUD\"," +
"\"value\":\"" + ep.EbayProductPrice.ToString() + "\"" +
"}" +
"}],";
jsonInventoryRequest += "\"shipToLocationAvailability\": " + "{" +
"\"quantity\":" + ep.EbayProductStockQuantity +
"},";
jsonInventoryRequest += "\"sku\": " + ep.EbayProductSKU.ToString() + "}";
if (commaCount < productsToProcess.Count())
jsonInventoryRequest += ",";
commaCount++;
sendEbayApiRequest = true;
}
jsonInventoryRequest +=
"]" +
"}";
And the Debug.WriteLine() output of the above JSON request is :
json string = {"requests": [{"offers": [{"availableQuantity":0,"offerId":"098772298312","price": {"currency": "AUD","value":"148.39"}}],"shipToLocationAvailability": {"quantity":0},"sku": 135779},{"offers": [{"availableQuantity":1,"offerId":"044211823133","price": {"currency": "AUD","value":"148.39"}}],"shipToLocationAvailability": {"quantity":1},"sku": 133607}]}
Here is the code in C# to send the request:
var ebayAppIdSetting = _settingService.GetSettingByKey(
"ebaysetting.appid", "");
var ebayCertIdSetting = _settingService.GetSettingByKey(
"ebaysetting.certid", "");
var ebayRuNameSetting = _settingService.GetSettingByKey(
"ebaysetting.appid", "");
var stringToEncode = ebayAppIdSetting + ":" + ebayCertIdSetting;
HttpClient client = new HttpClient();
byte[] bytes = Encoding.UTF8.GetBytes(stringToEncode);
var base64string = "Basic " + System.Convert.ToBase64String(bytes);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", base64string);
var stringContent = "?grant_type=client_credentials&" + "redirect_uri=" + ebayRuNameSetting + "&scope=https://api.sandbox.ebay.com/oauth/api_scope";
var requestBody = new StringContent(stringContent.ToString(), Encoding.UTF8, "application/json");
requestBody.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = client.PostAsync("https://api.sandbox.ebay.com/identity/v1/oauth2/token", requestBody);
The output I get when I do Debug.WriteLine("response.Content = " + response.Result); is:
response.Content = StatusCode: 401, ReasonPhrase: 'Unauthorized',
Version: 1.1, Content: System.Net.Http.StreamContent, Headers: {
RlogId:
t6ldssk%28ciudbq%60anng%7Fu2h%3F%3Cwk%7Difvqn*14%3F0513%29pqtfwpu%29pdhcaj%7E%29fgg%7E%606%28dlh-1613f3af633-0xbd
X-EBAY-C-REQUEST-ID: ri=HNOZE3cmCr94,rci=6kMHBw5dW0vMDp8A
X-EBAY-C-VERSION: 1.0.0 X-EBAY-REQUEST-ID:
1613f3af62e.a096c6b.25e7e.ffa2b377!/identity/v1/oauth2/!10.9.108.107!r1esbngcos[]!token.unknown_grant!10.9.107.168!r1oauth-envadvcdhidzs5k[]
Connection: keep-alive Date: Mon, 29 Jan 2018 00:04:44 GMT
Set-Cookie: ebay=%5Esbf%3D%23%5E;Domain=.ebay.com;Path=/
WWW-Authenticate: Basic Content-Length: 77 Content-Type:
application/json }
Can anyone see where I'm going wrong. Cheers
Ok so the authentication was failing because I was sending wrong authentication token. Needed to get oauth token from application tokens.
So instead of base64 encoding token like this:
var base64string = "Basic " + System.Convert.ToBase64String(bytes);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", base64string);
I needed to do the following:
url = "https://api.sandbox.ebay.com/sell/inventory/v1/bulk_update_price_quantity";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
//request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("Authorization", "Bearer **OAUTH TOKEN GOES HERE WITHOUT ASTERIKS**");
// Send the request
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(jsonInventoryRequest);
streamWriter.Flush();
streamWriter.Close();
}
// Get the response
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response != null)
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
// Parse the JSON response
var result = streamReader.ReadToEnd();
}
}

Error: (403) Forbidden

I'm trying to do a HttpWebRequest(POST) to send some data to a server. However I always got error: (403) Forbidden. This is my current code:
foreach (Patient patient in patients)
{
string[] names = patient.Nome.Split(' ');
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8090/ehr/rest/createPerson");
request.Headers.Add("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXh0cmFkYXRhIjp7Im9yZ2FuaXphdGlvbiI6IjY2NjYifSwiaXNzdWVkX2F0IjoiMjAxNi0wNC0yMlQxMzo0ODoyOS40ODRaIn0=.Fztrd8LR/FkBY2CJLjnl/qYYYjz1/vr4g01e8yTad/0=");
request.Accept = "application/json";
string tempUrl = "firstName=" + names[0];
tempUrl += "&lastName=" + names[names.Length - 1];
tempUrl += "&dob=" + patient.Data_Nasc;
tempUrl += "&role=pat";
tempUrl += "&sex=" + "M";
tempUrl += "&organizationUid=" + organization.Uid;
var data = Encoding.ASCII.GetBytes(tempUrl);
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);
stream.Close();
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
I know that there is a lot of questions about this error, but no answer resolve my problem. Im still getting error 403.
Next is the stacktrace:
at System.Net.HttpWebRequest.GetResponse()
at IndexDocClinicos.Classes.EhrData.createPersons() in c:\Users\Joaogcorreia\Desktop\EHR + Solr + IndexDocClinicos\Indexacao-de-Documentos-Clinicos\Indexação de Documentos Clinicos\IndexDocClinicos\Classes\EhrData.cs:line 163
at IndexDocClinicos.WebApiApplication.Application_Start() in c:\Users\Joaogcorreia\Desktop\EHR + Solr + IndexDocClinicos\Indexacao-de-Documentos-Clinicos\Indexação de Documentos Clinicos\IndexDocClinicos\Global.asax.cs:line 37
I already tried this POST with Insomnia and it works very well. So I have no ideia what is wrong. I also verified and the token is correct.
pls help
thanks =)

GetResponse throws 400 Bad request

Getting 400 bad Request When trying to get the Response from my HTTPS post request. Here is my code:
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://coupons.valassis.eu/capi/directPrint/"+offerID);
httpWebRequest.Credentials = new NetworkCredential(userName,Password);
WebHeaderCollection myWebHeaderCollection = httpWebRequest.Headers;
myWebHeaderCollection.Add("Authorization: Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(httpWebRequest.Credentials.ToString())));
myWebHeaderCollection.Add("x-valassis-country-code: uk");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "[{ \"consumerId\": \"000000000000001\", \"remoteConsumerId\": \"000000000000001\" , \"Barcode\": \"Itf: 04910033400000000000000001,Ean13:ccode\", \"Type\": \"j\", \"returnUrl\": \"http://www.durex.co.uk\",\"CouponDescription\" : \"Coupon For:\"" + this.FirstName + " " + this.SurName + "\" }]";
var serializer = new JavaScriptSerializer();
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (Stream streamReader =httpResponse.GetResponseStream())
{
using (StreamReader r = new StreamReader(streamReader))
{
var result = r.ReadToEnd();
}
}
}
}
catch (WebException e)
{
}
Any one knows what might be the problem? or How to solve this issue?
The JSON string that you create is invalid, as the CouponDescription property contains an odd number of quotes.
If i run this....
var FirstName = "Joe";
var SurName = "Bloggs";
var json = "[{ \"consumerId\": \"000000000000001\", \"remoteConsumerId\": \"000000000000001\" , \"Barcode\": \"Itf: 04910033400000000000000001,Ean13:ccode\", \"Type\": \"j\", \"returnUrl\": \"http://www.durex.co.uk\",\"CouponDescription\" : \"Coupon For:\"" + FirstName + " " + SurName + "\" }]";
I get...
[{ "consumerId": "000000000000001", "remoteConsumerId": "000000000000001" , "Barcode": "Itf: 04910033400000000000000001,Ean13:ccode", "Type": "j", "returnUrl": "http://www.durex.co.uk","CouponDescription" : "Coupon For:"Joe Bloggs" }]
Look at the CouponFor value, the quotes are not closed.
Tools like LINQPad and JSONLint are very useful for validating code snippets in these scenarios

Categories

Resources