Make a call request Etsy API in Restsharp - c#

I'm working with Etsy API . I got ConsumerKey , ConsumerSecret , OauthToken , OauthTokenSecret . Now i want to make request that need require Authorize
My code like this
var client = new OAuthRequest
{
Method = "GET",
Type = OAuthRequestType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ConsumerKey = ConsumerKey,
ConsumerSecret = ConsumerSecret,
Token = OauthToken,
TokenSecret = OauthTokenSecret,
RequestUrl = requestUrl,
};
requestUrl += "?" + client.GetAuthorizationQuery();
var restClient = new RestClient();
var restRequest = new RestRequest(requestUrl, Method.GET);
var result = restClient.Execute(restRequest).Content;
But i got result oauth_problem=token_rejected
Any help would be greatly appreciated.

Related

How To Pass Username and Password in the Body for Wordpress JWT Auth API

I have Wordpress and JWT Auth installed and I want to validate a username and password.
I simply want to pass the username and password through the JWT Token API using my C# code.
Here's the API link that's working in Postman:
https://xxxx/wp-json/jwt-auth/v1/token
I can only pass the username and password in the "Body" "Form-Data" fields with the key values "username" and "password" because parameters don't work with JWTAuth.
How do I pass these values as a "Body" "Form-Data" value using C#?
Here's my code:
string JWTAPI = "https://xxxx/wp-json/jwt-auth/v1/token";
var client = new HttpClient();
var uri = JWTAPI;
var jsonContent = "{ \"username\": \"test\", \"password\": \"test\"}";
string json = JsonConvert.SerializeObject(jsonContent);
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
var response_status = await client.PostAsync(uri, content);
var response_result = await response_status.Content.ReadAsStringAsync();
Never mind. I got it to work!
Just needed to remove:
string json = JsonConvert.SerializeObject(jsonContent);
TokenRequest Token;
public async Task TakeToken()
{
client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "username", "root" },
{ "password", "1111" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync($"{BaseUrl}/wp-json/jwt-auth/v1/token", content);
var responseString = await response.Content.ReadAsStringAsync();
Token = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenRequest>(responseString);
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Token.token);
}
public class TokenRequest
{
public string token;
public string user_email;
public string user_nicename;
public string user_display_name;
}

RestSharp C# HTTP POST Oauth 1

I am running into a difficulty with HTTP POST and Oauth 1, RestClient C#. I am able to make successful calls with HTTP GET and Oauth, but for some reason HTTP Post fails. I was able to make successful HTTP POST calls with same credentials using Postman, but not with RestSharp. Perhaps someone could help me figuring out the issue.
Here are the screenshots with working HTTP POST Oauth1 Postman call:
The Postman setup above works just fine, and here is what I have so far in C# and RestClient:
public bool CreateShippingTemplate(string storeProviderStoreId, string consumerKey, string consumerSecret, string oAuthToken, string oAuthTokenSecret)
{
string url = "/shipping/templates";
var request = GenerateSecureRequest(url, RequestType.POST, consumerKey, consumerSecret, oAuthToken, oAuthTokenSecret);
var dataObj = new //ShippingTemplate
{
title = "Test Title 2",
origin_country_id = "209",
primary_cost = "1",
secondary_cost = "1"
};
string dataObjJson = JsonConvert.SerializeObject(dataObj);
request.AddParameter("application/json", dataObjJson, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
request.Method = Method.POST;
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
var response = _restClient.ExecuteAsPost(request,"POST");
return true;
}
private RestRequest GenerateSecureRequest(string url, RequestType requestType, string consumerKey, string consumerSecret, string oAuthToken, string oAuthTokenSecret)
{
OAuthBase oAuth = new OAuthBase();
string nonce = oAuth.GenerateNonce();
string timeStamp = oAuth.GenerateTimeStamp();
string normalizedUrl;
string normalizedRequestParameters;
string relativeUri = url;
string sig = oAuth.GenerateSignature(new Uri(BASE_URL.ToString() + relativeUri), consumerKey, consumerSecret, oAuthToken, oAuthTokenSecret, requestType.ToString(), timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters);
var request = new RestRequest(relativeUri);
request.Resource = string.Format(relativeUri);
request.Method = Method.GET;
request.AddParameter("oauth_consumer_key", consumerKey);
request.AddParameter("oauth_token", oAuthToken);
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);
return request;
}
I tried many things with RestClient and C#, nothing worked. What am I missing, in order to match the working Postman request. HTTP GET is working for me in RestSharp, only HTTP Post is not working.
Thank you
Ok, I finally got my working, went the same wrong way trying to implement signature creation myself.. as I badly interpreted PostMan RestSharp code.
This could be done much easier as RestSharp does it all for you! I wish this was the version PostMan gave as a "code" example. Anyway, this works for me in C# (quick console app):
const string consumer_key = "abcd1234";
const string consumer_secret = "1234abcd";
const string access_token = "1a2b3c4d";
const string token_secret = "a12b3c4d";
const string URL = "https://aa.web.site.net/history/api/account/123456789/givemedata/search?offset=0&limit=50";
static void Main(string[] args)
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
var client = new RestClient(URL);
client.Authenticator = OAuth1Authenticator.ForAccessToken(consumer_key, consumer_secret, access_token, token_secret, RestSharp.Authenticators.OAuth.OAuthSignatureMethod.HmacSha1);
client.Timeout = -1;
var request = new RestRequest(URL, Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\"start\": {\"from\": 1583074556000, \"to\": 1588258556000 } }", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Console.ReadKey();
}
Yes, I know, no headers, no param sorting and hashing.. no nonce-nse :)
thanks Pete, this code saves me hours of try and error!
the only code I added here is Realm
OAuth1Authenticator lAuthenticator = OAuth1Authenticator.ForAccessToken(consumer_key, consumer_secret, access_token, token_secret, RestSharp.Authenticators.OAuth.OAuthSignatureMethod.HmacSha256);
lAuthenticator.Realm = "my_Realm";
client.Authenticator = lAuthenticator;

Setting dynamic baseUrl for Get Request RestClient

I am wanting to dynamically change my baseUrl for my RestClient depending on what token is being run.
This is for the deputy roster systems attempting to get Roster data out but cannot figure out how to get a custom baseUrl for each token
public List<DeputyRosterData> RosterData(string url, int? actual, int? roster)
{
BaseUrl = "e1f5c520093734.au.deputy.com"; //Error on this line but to show you what I need
var request = Request("/api/v1/resource/Roster");
var result = _client.Execute<List<DeputyRosterData>>(request);
return result.Data;
}
I think, It's useful for u
var client = new RestClient();
string baseURL = "http://northwind.servicestack.net";
string apiURL = baseURL + "/" + "customers?format=json";
client = new RestClient(apiURL); // 1 URL
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
baseURL = "https://jsonplaceholder.typicode.com";
apiURL = baseURL + "/posts/1";
client = new RestClient(apiURL);//2 URL
request = new RestRequest(Method.GET);
response = client.Execute(request);

Not getting Profile Pic and Email address from linkedin api in MVc4

Here is my code please let me know why am not able to get emailid and profile pic.
public class LinkedInController : Controller
{
public ActionResult index()
{
return AuthenticateToLinkedIn();
}
static string token_secret = "";
public ActionResult AuthenticateToLinkedIn()
{
var credentials = new OAuthCredentials
{
CallbackUrl = "http://localhost:7326/Linkedin/callback",
ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
Verifier = "123456",
Type = OAuthType.RequestToken
};
var client = new RestClient { Authority = "https://api.linkedin.com/uas/oauth", Credentials = credentials };
var request = new RestRequest { Path = "requestToken" };
request.AddParameter("scope", "r_emailaddress");
RestResponse response = client.Request(request);
string content = response.Conten
var contents = HttpUtility.ParseQueryString(response.Content)
var token = response.Content.Split('&')[0].Split('=')[1];
token_secret=contents["oauth_token_secret"];
Response.Redirect("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token);
return null;
}
string token = "";
string verifier = "";
public ActionResult Callback()
{
token = Request["oauth_token"];
verifier = Request["oauth_verifier"];
var credentials = new OAuthCredentials
{
ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
Token = token,
TokenSecret = token_secret,
Verifier = verifier,
Type = OAuthType.AccessToken,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
Version = "1.0"
};
var client = new RestClient { Authority = "https://api.linkedin.com/uas/oauth", Credentials = credentials, Method = WebMethod.Post };
var request = new RestRequest { Path = "accessToken" };
request.AddParameter("scope", "r_emailaddress");
RestResponse response = client.Request(request);
string content = response.Content;
var contents = HttpUtility.ParseQueryString(response.Content);
var accessToken =contents["oauth_token"];
var accessTokenSecret=contents["oauth_token_secret"];
var people = new LinkedInService(accessToken, accessTokenSecret).GetCurrentUser();
String companyName = people.FirstName;
return Content(companyName);
}
}
I am using Hammock and i am getting first name and last name and title and all i have enabled the r_emailadress in LinkedIn Portal but please am not able to get these information.
The only scope you're using is r_emailaddress. To get the pic, I think you need to use r_basicprofile. I can't see a field in the docs called 'emailid', only email-address.
https://developer.linkedin.com/docs/fields/basic-profile

500 px api with C# throwing 500 Internal Server Error

I am trying to implement 500px API with C#. I am able to authenticate user with 500px API but I am unable to get the access_token in exchange of response_token which leaves my third step of Oauth 1.0 incomplete. I am able to authorize user and get oauth_token and oauth_verifier but when I use this oauth_token for making following request :-
https://api.500px.com/v1/oauth/access_token
500 Internal Server Error along with the following screen gets thrown
I have debugged my code like thousand times, tried different ways to form URL, added various parameters to the request but no help. I am very badly stuck as almost no information is available on 500px developer website or on web for using this api in C#. I have reached a dead-end!
Following is my code:-
1.]For requesting token and authorizing user :-
string normalizedUrl;
string normalizedRequestParameters;
OAuth.OAuthBase myOAuth = new OAuth.OAuthBase();
try
{
Uri uri = new Uri("https://api.500px.com/v1/oauth/request_token");
string consumerKey = "u26X4av9ydNPd7kteT7bunfcdjHqVttYWIDOC1lA";
string consumerSecret = "73iaFPqCR4xkH3dgYIcPauTqhI6tMHWChDivnOP7";
string timeStamp = myOAuth.GenerateTimeStamp();
string nonce = myOAuth.GenerateNonce();
myOAuth.includeVersion = true;
string signature = myOAuth.GenerateSignature(uri, consumerKey, consumerSecret,
"", "", "GET", timeStamp, nonce, OAuth.OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out normalizedRequestParameters);
string authorizationUrl = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
Uri signInUrl = new Uri(authorizationUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(signInUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stIn = new StreamReader(response.GetResponseStream());
string responseString = stIn.ReadToEnd();
stIn.Close();
//oauth_token=cf40227bb7ede4d6e56ff790324761b3&oauth_token_secret=0bcb59dff2c1d095739c86c534fc62d7ed224fecfe8744d48c9c95f36211382f
if (responseString.Contains("oauth_token=") && responseString.Contains("oauth_token_secret="))
{
String RespToken = responseString.Split('&')[0].Replace("oauth_token=", "");
String RespSecret = responseString.Split('&')[1].Replace("oauth_token_secret=", "");
uri = new Uri("https://api.500px.com/v1/oauth/authorize");
timeStamp = myOAuth.GenerateTimeStamp();
nonce = myOAuth.GenerateNonce();
myOAuth.includeVersion = true;
signature = myOAuth.GenerateSignature(uri, consumerKey, consumerSecret, RespToken
, RespSecret, "GET", timeStamp, nonce, OAuth.OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out normalizedRequestParameters);
Console.WriteLine("Signature=="+signature);
authorizationUrl = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
Uri signInUrl1 = new Uri(authorizationUrl);
webBrowser1.Navigate(signInUrl1);
}
2.]After User clicks on Authorise this application for getting access_token:-
private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string parameters;
string normalizedUrl;
string normalizedRequestParameters;
string consumerKey = "u26X4av9ydNPd7kteT7bunfcdjHqVttYWIDOC1lA";
string consumerSecret = "73iaFPqCR4xkH3dgYIcPauTqhI6tMHWChDivnOP7";
OAuth.OAuthBase myOAuth = new OAuth.OAuthBase();
try
{
if (e.Url.ToString().Contains("https://www.xyz.com/"))
{
String url = (e.Url.ToString()).Replace("https://www.xyz.com/?","");
if( url.Contains("oauth_token="))
{
string OAuthToken = url.Split('&')[0].Replace("oauth_token=", "");
var uri = "https://api.500px.com/v1/oauth/access_token";
OAuthBase oAuth = new OAuthBase();
var nonce = oAuth.GenerateNonce();
var timeStamp = oAuth.GenerateTimeStamp();
var signature = oAuth.GenerateSignature(new Uri(uri), consumerKey, consumerSecret,
OAuthToken, String.Empty, "POST", timeStamp, nonce,
OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
signature = HttpUtility.UrlEncode(signature);
var requestUri = normalizedUrl + "?" + "oauth_callback=https://www.xyz.com" +"?"+ normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
Console.WriteLine(requestUri);
var request = (HttpWebRequest)WebRequest.Create(requestUri.ToString());
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/json";
// request.ContentType = "application / x - www - form - urlencoded";
//request.Credentials = CredentialCache.DefaultCredentials;
//request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)";
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var accessToken = reader.ReadToEnd();
}
}
catch(Exception ex)
{
Console.Writeln(ex.toString());
}
}
Now following is the line where my code is breaking:-
var response = request.GetResponse();
Completely at my wits end on this issue, not able to get to the root of it. Any help any directions will be highly appreciated. Any suggestions would be of great help!!
Thanks a ton in advance!
Here's what to do:
Use GET rather than POST (POST may work; I've not tried it and have had little success with 500px and POSTing)
Include the oauth_verifier you received during the authorisation step in the query URL
Sign the entire query using your consumer key and request token secret (returned in step 1)
Code snippet which should return "oauth_token=...&oauth_token_secret=..." in the HTTP reply body.
Make sure your OAuth implementation doesn't strip out any parameters beginning with "oauth_"! Mine was and it was stripping out the oauth_verifier parameter which is required by 500px.
OAuth.OAuthBase oauth = new OAuth.OAuthBase();
string strUrl = "";
string strParams = "";
string signature = oauth.GenerateSignature(new Uri(API_URL + "oauth/access_token?oauth_verifier=" + this.oauthVerifier),
this.consumerKey, this.consumerSecret, this.oauthToken, this.requestTokenSecret,
"GET", oauth.GenerateTimeStamp(), oauth.GenerateNonce(),
OAuth.OAuthBase.SignatureTypes.HMACSHA1,
out strUrl, out strParams);
string authorizationUrl = strUrl + "?" + strParams + "&oauth_signature=" + System.Web.HttpUtility.UrlEncode(signature);
Debug.WriteLine("url>" + authorizationUrl);
Response reply = SendGetRequest(authorizationUrl);
if (reply.Success)
{
Debug.WriteLine("access_token>" + reply.Content);

Categories