OAuth2 endpoint post request Xero - asp.net

First up, I'm not using the Xero api. This is more an OAuth2 questions than Xero specifically I think.
Not quite sure if the issue is a general OAuth2 problem or a Xero implementation of OAuth2. I can successfully authenticate, get my tokens etc from Xero. I can even make successful Get requests to their endpoints for Invoices and contacts. My problem is trying to POST anything, i.e. create an invoice.
The server responds with, 400 Bad request. I've confirmed by actual post data is correct by putting the XML into their API tester and all is good there.
Shouldn't a post request be a standard httpwebequest, (POST) with the query string ?oauth_signature=[sig here], and the actual post data URL encoded and sent via stream? Is my implementation correct and should I be looking elsewhere for the problem? Is the data sent in the form supposed to be included in the signature?
{
byte[] reqData = encode.GetBytes(postData);
HttpWebRequest request = WebRequest.CreateHttp(url + querystring) as HttpWebRequest;
request.Method = "POST";
try {
using (Stream stream = request.GetRequestStream) {
stream.Write(reqData, 0, reqData.Length);
}
using (HttpWebResponse response = request.GetResponse) {
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
dynamic responseFromServer = reader.ReadToEnd();
return responseFromServer;
}
} catch (Exception ex) {
}
}

Xero uses OAuth1.0a, rather than OAuth2. The OAuth signature needs to be supplied as a header rather than a query string. I believe it should be exactly the same as the successful GET requests you're making.
https://oauth.net/core/1.0a/#rfc.section.5.4.1:
The OAuth Protocol Parameters are sent in the Authorization header the following way:
Parameter names and values are encoded per Parameter Encoding.
For each parameter, the name is immediately followed by an '=' character (ASCII code 61), a '"' character (ASCII code 34), the parameter value (MAY be empty), and another '"' character (ASCII code 34).
Parameters are separated by a comma character (ASCII code 44) and OPTIONAL linear whitespace per [RFC2617].
The OPTIONAL realm parameter is added and interpreted per [RFC2617], section 1.2.

Update for those finding this now, Xero API now has OAuth2 in public Beta
https://developer.xero.com/documentation/oauth2/overview

Related

Formulating POST request to CoinSpot API

I am pulling my hair out trying to query the CoinSpot API.
The endpoint for the Read Only API is: https://www.coinspot.com.au/api/ro
The documentation states:
All requests to the API will need to include the following security
data.
Headers: key - Your API key generated from the settings page sign -
The POST data is to be signed using your secret key according to
HMAC-SHA512 method. Post Params: nonce - Any integer value which must
always be greater than the previous requests nonce value.
I try to query the 'List My Balances' endpoint via: https://www.coinspot.com.au/api/ro/my/balances
However, the code I have formulated below always returns an error: "invalid/missing nonce".
I have tried so many different variations and approaches but it is always the same error.
require(httr)
key <- "68z...39k"
secret <- "71A...48i"
result <- POST("https://www.coinspot.com.au/api/ro/my/balances",
body = list('nonce'=as.integer(as.POSIXct(Sys.time()))), add_headers("key"=key,"sign"=openssl::sha512("https://www.coinspot.com.au/api/ro/my/balances",key = secret)))
content(result)
Any help much appreciated.
Ive struggled with this too- the coinspot API guide isn't very clear.
I figured out you are meant to encode the postdata in correct json format using sha512 and add that to the sign header. See example below querying account balances on v2 of the api.
require(httr)
api_key = "68z...39k"
api_secret = "71A...48i"
base_url = "https://www.coinspot.com.au/api/v2/ro"
request = "/my/balances"
nonce = as.character(as.integer(Sys.time()))
postdata = paste0('{"nonce":"',nonce,'"}') # important to get the quotes correct
api_sign = digest::hmac(api_secret, postdata, algo="sha512",raw=F)
result = POST(paste0(base_url, request),
body = list("nonce"=nonce),
add_headers(c("key"=api_key,
"sign"=api_sign)),
encode="json"
)
cat(rawToChar(result$content))
You would change what is in postdata based on what you are doing with the API- this is a simple example to build on. If you want to see what postdata should look like prior to encryption in sign, use cat(rawToChar(result$request$options$postfields)) after making a request.
For me, I was missing the JSON string encoded postdata in the body, including the nonce. As soon as I added that, it started working.
Heres my code in c# using Restsharp and Newtonsoft
//put the nonce at the beginning
JObject joBody = JObject.Parse(#"{'nonce': '" + DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() + "'}");
joBody.Merge(originalBody);
var client = new RestClient(_coinspotSettings.BaseURL);
RestRequest request = new RestRequest(endpoint, Method.POST);
request.AddJsonBody(JsonConvert.SerializeObject(joBody));
request.AddHeader("key", coinspotAccount.APIKey);
request.AddHeader("sign", SignData(coinspotAccount, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(joBody))).ToLower());
request.AddHeader("Content-Type", "application/json");
private string SignData(CoinspotAccount coinspotAccount, byte[] JSONData)
{
var HMAC = new HMACSHA512(Encoding.UTF8.GetBytes(coinspotAccount.APISecret));
byte[] EncodedBytes = HMAC.ComputeHash(JSONData);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i <= EncodedBytes.Length - 1; i++)
stringBuilder.Append(EncodedBytes[i].ToString("X2"));
return stringBuilder.ToString();
}

How to stop ASP .NET from JSONifying JSON

I am currently trying to wrap an internal API and make it external. To do so, I am trying to relay the JSON responses from the internal API and send that exact response when someone makes a get request. Instead, ASP .NET is JSONifying that son and adding extra back slashes as escape characters (when in fact those slashes are really escape slashes put in by the internal api).
How can i get it so asp does not jsonify the string
You can write your json data directly to response and set right content headers.
public HttpResponseMessage GetData()
{
var json = "\"value\": \"da\\ta\"";
var resp = Request.CreateResponse(HttpStatusCode.OK);
resp.Content = new StringContent(json);
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
resp.Content.Headers.ContentEncoding = //your json encoding, you can get it from response inner API
return resp;
}

web api (asp.net) - sending data via post method

I'm trying to pass data via post method from my client to a server.
I'm using WebApi to do so.
This i the code i used:
client:
var client = new RestClient();
client.EndPoint = #"http://localhost:57363/hello";
client.Method = HttpVerb.POST;
client.PostData = "{value: Hello}";
var json = client.MakeRequest();
Console.WriteLine(json);
Console.Read();
server:
// POST api/<controller>
public string Post([FromBody]string value)
{
return value + ", world.";
}
The server responds as expected when using postman. However, the client passes a null value instead of the real value.
What am i doing wrong?
First of all a correct json would look like "{value: 'Hello'}".
I use json-online to easily validate such inline json.
On the other hand, I think that you should send just the value in this case, not the entire json (because you are trying to resolve a simple type,a string), so the client should send a request like:
client.PostData = "'Hello'";

How to read xml response generated by HTTP POST Interface

I generate request to a certain API which is mentioned here for sending an sms http://help.voxeo.com/go/help/evolution.sms.postapi
The request generates an XML response as follow
<rsp stat="ok">
<success msg="accepted" transactionid="2e47fe224d25559a696a7bdddec1828b" messageid="cf0d21f067e5b386a2e042134687eb5c"/>
</rsp>
I want to read if rsp stat in response is ok or fail how can i do it .
These are the first two lines how can i get particular xml tag out of response stream
HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();
Stream content = response.GetResponseStream();
Why not use XmlDocument to parse the XML. For example,
using(var reader = new StreamReader(content))
{
var doc = new XmlDocument();
doc.LoadXml(reader.ReadToEnd());
// you may want to compare case in-sensitive
if (doc.DocumentElement.Attributes["stat"].Value == "ok")
{
// success
}
}
(There is also Load method that would load from stream directly but I am not sure if it expects xml declaration at the beginning or not)
Yet another alternative is using XmlReader in case response could be lengthy and you wants to parse the initial bits as soon as its available.
try to read with XmlTextReader (http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader%28v=vs.71%29.aspx)

WCF Service Call during post

I have given
[WebGet(UriTemplate = "/{year}/{issue}/{article}")]
Article GetArticle(string year, string issue, string article);
[OperationContract]
[WebInvoke(UriTemplate = "/{year}/{issue}",Method="POST")]
Article AddArticle(string year, string issue, Article article);
My URL is http://localhost:1355/Issues.svc/
if I give this I am fetching all data from the database
http://localhost:1355/Issues.svc/2010/June/A
GetArticle method fires for the filtered data to bring from db.
Similarly I have to call the Add Article(WebInvoke) method to insert data in to the database.
How should I call this method in the browser
how my url should be should I give method=post
check this post help you to achieve the task you want :Create REST service with WCF and Consume using jQuery
You won't be able to send an HTTP post from a browser by just modifying the URL. You'll have to have a web page with a HTML form, some Javascript code, some server-side code, or something else that has the ability to make an HTTP POST request to your service URL.
If you are just wanting to test your service while in development, here's a good HTTP debugging tool that you might want to check out: http://fiddler2.com
You can't use post it using browser url.
Try this code
//Creating the Web Request.
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://localhost/DemoApp/Default.aspx") as HttpWebRequest;
//Specifing the Method
httpWebRequest.Method = "POST";
//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "Username=username&password=password";
//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
Source : http://www.dotnetthoughts.net/2009/11/10/post-data-using-httpwebrequest-in-c-sharp/

Resources