Access Etsy API oauth using c# RestSharp - c#

I set up a developer acct under our shop, to access our sales receipts. I decided to use RestSharp to make my requests. I have proved it works for none Oauth required calls. I have successfully received my accessToken and accessTokenSecret. So i use those along with the customerKey and customerSecret to make a ForProtectedResource call, for a oauth request as follows but always receive "This method requires authentication".
I'm hoping its something simple I'm missing. I thought, all I need to make any call are those four items correct? Once I have those four items I don't have to request or access token anymore, correct? Thanks
var access_token = "#########################";
var access_token_secret = "########";
var baseUrl = "https://openapi.etsy.com/v2";
var client = new RestClient(baseUrl);
client.Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey,
consumerSecret,
access_token,
access_token_secret);
var request = new RestRequest("shops/########/receipts");
request.Method = Method.GET;
request.AddParameter("api_key", consumerKey);
client.ExecuteAsync(request, response =>
{
var r = response;
});

After some trial and error I finally wrapped my head around OAuth and the way Etsy implements it. The api_key parameter is only to be used when you're calling a none OAuth required method. Otherwise you have to send it all the required OAuth params. Below is working code. I leveraged RestSharp, as well as this OAuth base I found here. Hope this help some poor sap from staring at crappy code for 3 days (like yours truly).
var restClient = new RestClient(baseUrl);
OAuthBase oAuth = new OAuthBase();
string nonce = oAuth.GenerateNonce();
string timeStamp = oAuth.GenerateTimeStamp();
string normalizedUrl;
string normalizedRequestParameters;
string sig = oAuth.GenerateSignature(new Uri(baseUrl + MethodLocation), consumerKey, consumerSecret, Accesstoken, AccessTokenSecret, "GET", timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters);
// sig = HttpUtility.UrlEncode(sig);
var request = new RestRequest(MethodLocation);
request.Resource = string.Format(MethodLocation);
request.Method = Method.GET;
// request.AddParameter("api_key", consumerKey);
request.AddParameter("oauth_consumer_key", consumerKey);
request.AddParameter("oauth_token", Accesstoken);
request.AddParameter("oauth_nonce", nonce);
request.AddParameter("oauth_timestamp", timeStamp);
request.AddParameter("oauth_signature_method", "HMAC-SHA1");
request.AddParameter("oauth_version", "1.0");
request.AddParameter("oauth_signature", sig);
restClient.ExecuteAsync(request, response =>
{
var r = response;
});

Related

C# Oracle Rest API, Authentication Issue

I am trying to use Ocacle's Financial REST API and I'm having trouble making it work in C# in VS2019.
I can confirm the restful call works using Postman, so I know my credentials are fine but I must be missing something trying this with in code.
So URL is like so:
http://MYCLOUDDOMAIN/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail
So I stick that in postman, put in my credentials (basic auth) and it works find. In VS I've tried both the RestSharp way and basic HTTPRequest way as follows:
HttpWebRequest r = (HttpWebRequest)WebRequest.Create("/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger US,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail");
r.Method = "GET";
string auth = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("Username" + ":" + "Password"));
r.Headers.Add("Authorization", "Basic" + " " + auth);
r.ContentType = "application/vnd.oracle.adf.resourcecollection+json";
using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
{
int b = 0;
}
RestSharp:
var client = new RestClient("http://MYCLOUDDOMAIN/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger US,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail");
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("UserName", "Password");
//Tried authorization this way as well.
//JObject AuthRequest = new JObject();
//AuthRequest.Add("Username", "UserName");
//AuthRequest.Add("Password", "Password");
var request = new RestRequest();
request.Method = Method.GET;
request.RequestFormat = DataFormat.Json;
//request.AddParameter("text/json", AuthRequest.ToString(), ParameterType.RequestBody);
request.AddHeader("Content-Type", "application/vnd.oracle.adf.resourcecollection+json");
request.AddHeader("REST-Framework-Version", "1");
var response = client.Get(request);
No matter what I try I am always 401 not authorized. I suspect its some kind of header thing? I can't see the raw request header in postman
I am new to REST. I am used to using WSDLs soap services.
Try this.
var handler = new HttpClientHandler
{
Credentials = new NetworkCredential("username", "password")
};
using (var client = new HttpClient(handler))
{
var result = await client.GetAsync("url");
}
Good luck!
I figured out what the problem was.
In postman, it was fine with the URL I posted being HTTP but in C# code it was not. I switched the URL to HTTPS and it started working just fine.

Example of OAuth authenticated request using .NET framework

The Node.JS code below sends 0-legged OAuth authenticated request to the API:
'use strict';
var OAuth = require('OAuth');
var express = require('express');
var app = express();
var oauth = new OAuth.OAuth(
'http://example.com/oauth/request_token',
'http://example.com/oauth/access_token',
'mykey',
'none',
'1.0',
null,
'HMAC-SHA1'
);
app.get('/', function (req, res) {
oauth.get(
'http://example.com/api',
'token123',
'tokensecret123',
function (error, data, response){
data = JSON.parse(data);
res.json(data);
});
});
I need to convert this code to C# or VB.NET. Any sample of OAuth authenticated request in .Net will help too.
I do it with the library RestSharp which helps to deal with REST API.
The code below send a request to get a token from the OAuth:
var restClient = new RestClient();
restClient.BaseUrl = new Uri("theApiBaseUrl");
string encodedCredentials = Convert.ToBase64String(Encoding.Default.GetBytes($"yourAppId:yourSecret"));
// change the request below per the API requirement
RestRequest request = new RestRequest("theApiUrlForAuthentication", Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Authorization", $"Basic {encodedCredentials}");
request.AddQueryParameter("grant_type", "client_credentials");
request.AddQueryParameter("scope", "api");
IRestResponse response = restClient.Execute(request);
// the token should be in the JSON string response.Content
// now you'll want to deserialize the JSON to get the token
var jsonWithToken = MyFunctionToGetToken(response.Content);
Now you have the token in order to do authenticated calls to the API:
var restClient = new RestClient();
restClient.BaseUrl = new Uri("theApiBaseUrl");
RestRequest request = new RestRequest("theApiEndpoint", Method.GET);
request.AddHeader("Accept", "application/hal+json");
request.AddHeader("profile", "https://api.slimpay.net/alps/v1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", $"Bearer {token}");
RestClient.Execute(request);
Each API is different, so you'll surely have to modify my code (add or remove headers, encoding the credentials, ...) so that it works for you.
Thank you #Guillaume Sasdy for steering me towards RestSharp. Here is a working solution that works the same way as the node.js code in my question.
Since API I'm accessing is using 0-legged OAuth, the Access Token and Access Secret are known upfront and make things much easier.
const string consumerKey = "mykey";
const string consumerSecret = "none";
var baseUrl = "https://example.com";
var client = new RestClient(baseUrl);
var request = new RestRequest("/api");
client.Authenticator = OAuth1Authenticator.ForProtectedResource(
consumerKey, consumerSecret, "token123", "tokensecret123"
);
var response = client.Execute(request);

Why does my OAuth signature not match when connecting to WordPress via OAuth 1.0 in C#?

I am trying to complete the first step in the OAuth 1.0 authentication process and retrieve an unauthorized request token.
I keep getting a 401 OAuth signature does not match error from WordPress. I know the problem is with the way I am hashing my signature because when I use Postman, the signature I calculate is different than the signature that Postman calculates. Also I can successfully retrieve and unauthorized request token via Postman.
Where I am going wrong in computing my hash? I'm using HMAC-SHA1.
private void AuthorizeWP()
{
string requestURL = #"http://mywordpressurl.com/oauth1/request";
UriBuilder tokenRequestBuilder = new UriBuilder(requestURL);
var query = HttpUtility.ParseQueryString(tokenRequestBuilder.Query);
query["oauth_consumer_key"] = "myWordPressKey";
query["oauth_nonce"] = Guid.NewGuid().ToString("N");
query["oauth_signature_method"] = "HMAC-SHA1";
query["oauth_timestamp"] = (Math.Truncate((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds)).ToString();
string signature = string.Format("{0}&{1}&{2}", "GET", Uri.EscapeDataString(requestURL), Uri.EscapeDataString(query.ToString()));
string oauth_Signature = "";
using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes("myWordPressSecret")))
{
byte[] hashPayLoad = hmac.ComputeHash(Encoding.ASCII.GetBytes(signature));
oauth_Signature = Convert.ToBase64String(hashPayLoad);
}
query["oauth_signature"] = oauth_Signature;
tokenRequestBuilder.Query = query.ToString();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(tokenRequestBuilder.ToString());
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
I realize now what I was doing wrong.
With OAuth 1.0 when you generate the bytes for your hash key, you have to concatenate your consumer/client secret and the token with an '&' in the middle even if you don't have a token.
Source: https://oauth1.wp-api.org/docs/basics/Signing.html
So in my code above:
using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes("myWordPressSecret")))
needs to be:
using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes("myWordPressSecret&"))

Azure ACS get token using RestSharp 415 error

The following is the code sample provided by msdn for obtaining an SWT token from azure ACS (Access Control Service):
private static string GetTokenFromACS(string scope)
{
string wrapPassword = pwd;
string wrapUsername = uid;
// request a token from ACS
WebClient client = new WebClient();
client.BaseAddress = string.Format(
"https://{0}.{1}", serviceNamespace, acsHostUrl);
NameValueCollection values = new NameValueCollection();
values.Add("wrap_name", wrapUsername);
values.Add("wrap_password", wrapPassword);
values.Add("wrap_scope", scope);
byte[] responseBytes = client.UploadValues("WRAPv0.9/", "POST", values);
string response = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine("\nreceived token from ACS: {0}\n", response);
return HttpUtility.UrlDecode(
response
.Split('&')
.Single(value => value.StartsWith("wrap_access_token=", StringComparison.OrdinalIgnoreCase))
.Split('=')[1]);
}
I am trying to replicate the code using RestSharp:
var request = new RestRequest("WRAPv0.9", Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("wrap_name", uid, ParameterType.RequestBody);
request.AddParameter("wrap_password", pwd, ParameterType.RequestBody);
request.AddParameter("wrap_scope", realm, ParameterType.RequestBody);
RestClient client = new RestClient(
string.Format(#"https://{0}.{1}", serviceNamespace, acsHostUrl));
client.ExecuteAsync(request, Callback);
I tried other variations of the above code but to no avail. I keep recieving a 415 error stating that:
415 Unsupported Media Type T8000 Content-Type 'text/plain' is not
supported. The request content type must be
'application/x-www-form-urlencoded'.
I am not a Fiddler expert but with my limited experience with it I was not able to inspect my outgoing http request because it is encrypted.
I would appreciate advice on solving the issue.
You can try to leave out the AddHeader method call and instead set the Content-Type as the first AddParameter.
The issue is described here.

Getting signature_invalid calling oauth/request_token for Etsy's API using RestSharp

I'm trying to use RestSharp to access Etsy's API. Here's the code I'm using attempting to get an OAuth access token:
var authenticator = OAuth1Authenticator.ForRequestToken(
ConfigurationManager.AppSettings["ApiKey"],
ConfigurationManager.AppSettings["ApiSecret"]);
// same result with or without this next line:
// authenticator.ParameterHandling = OAuthParameterHandling.UrlOrPostParameters;
this.Client.Authenticator = authenticator;
var request = new RestRequest("oauth/request_token")
.AddParameter("scope", "listings_r");
var response = this.Client.Execute(request);
Etsy tells me that the signature is invalid. Interestingly enough, when I enter the timestamp and nonce values generated by the request into this OAuth signature validation tool, the signatures don't match. Moreover, the URL generated by the tool works with Etsy where the one generated by RestSharp doesn't. Is there something I'm doing wrong or something else I need to configure with RestSharp?
Note: I'm using the version of RestSharp provided by their Nuget package, which at the time of this posting is 102.5.
I finally was able to connect to the Etsy API with RestSharp using OAuth. Here is my code -- I hope it works for you...
RestClient mRestClient = new RestClient();
//mRestClient.BaseUrl = API_PRODUCTION_URL;
mRestClient.BaseUrl = API_SANDBOX_URL;
mRestClient.Authenticator = OAuth1Authenticator.ForRequestToken(API_KEY,
API_SHAREDSECRET,
"oob");
RestRequest request = new RestRequest("oauth/request_token", Method.POST);
request.AddParameter("scope",
"shops_rw transactions_r transactions_w listings_r listings_w listings_d");
RestResponse response = mRestClient.Execute(request);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
return false;
NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(response.Content);
string oauth_token_secret = queryString["oauth_token_secret"];
string oauth_token = queryString["oauth_token"];
string url = queryString["login_url"];
System.Diagnostics.Process.Start(url);
// BREAKPOINT HERE
string oauth_token_verifier = String.Empty; // get from URL
request = new RestRequest("oauth/access_token");
mRestClient.Authenticator = OAuth1Authenticator.ForAccessToken(API_KEY,
API_SHAREDSECRET,
oauth_token,
oauth_token_secret,
oauth_token_verifier);
response = mRestClient.Execute(request);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
return false;
queryString = System.Web.HttpUtility.ParseQueryString(response.Content);
string user_oauth_token = queryString["oauth_token"];
string user_oauth_token_secret = queryString["oauth_token_secret"];
The user_oauth_token and user_oauth_token_secret are the user's access token and access token secret -- these are valid for the user until the user revokes access.
I hope this code helps!

Categories