How to get admin token in magento 2.1.8? - c#

I'm trying to get an admin token from Magento version 2.1.8 in c# using well-known code that works for all except me. Could not understand where is the problem.
In response I get:
ErrorException = null, Content= "{\" message \ ": \" Request does not match any path. \ ", \" trace \ ": null}"
public Magento(string magentoUrl)
{
//Relative URL needs to be Specified
var endpoint = "/rest/V1/integration/admin/token";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var _restClient = new RestClient(magentoUrl);
var request = new RestRequest(endpoint, Method.POST);
//Initialize Credentials Property
var userRequest = new Credentials { username = "reewrew", password = "rwerwerw" };
var inputJson = JsonConvert.SerializeObject(userRequest);
//Request Header
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
//Request Body
request.AddParameter("application/json", inputJson, ParameterType.RequestBody);
var response = _restClient.Execute(request);
var token = response.Content;
}

I found the problem. I use HTTP instead of HTTPS in URL.

Related

ASP.NET C# curl call with OAuth not working

I am trying to do this curl call to the new yahoo weather api with OAuth 1 like so:
[HttpGet]
public HttpResponseMessage getWeather()
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://weather-ydn-yql.media.yahoo.com/");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", "OAuth oauth_consumer_key = \"(MY CONSUMER KEY)\", oauth_signature_method = \"HMAC-SHA1\", oauth_timestamp = \"1547473450\", oauth_nonce = \"Ll7ArdU1yN0\", oauth_version = \"1.0\", oauth_signature = \"(MY GENERATED SIGNATURE FROM POSTMAN)\"");
//httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", "oauth_consumer_key = \"(MY CONSUMER KEY)\", oauth_signature_method = \"HMAC-SHA1\", oauth_timestamp = \"1547472939\", oauth_nonce = \"vu3HE92s6A3\", oauth_version = \"1.0\", oauth_signature = \"(MY GENERATED SIGNATURE FROM POSTMAN)\"");
HttpResponseMessage response = httpClient.GetAsync("forecastrss?location=hamilton&format=json").Result;
return response;
}
}
But when I run this it returns this error:
Please provide valid credentials. OAuth
oauth_problem="OST_OAUTH_PARAMETER_ABSENT_ERROR",
realm="yahooapis.com"
So it appears that my OAuth parameters are missing. My Question is how do I do a curl in ASP.NET C# with OAuth 1 authentication?
Figured it out using RestClient
var client = new RestClient("http://weather-ydn-yql.media.yahoo.com/forecastrss?location=hamilton&format=xml");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "ac0c256b-e727-4b01-b4fe-edd8b7d7073a");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Authorization", "OAuth oauth_consumer_key="(MY CONSUMER KEY)",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1547481203",oauth_nonce="304ixaov43G",oauth_version="1.0",oauth_signature="(MY GENERATED SIGNATURE FROM POSTMAN)"");
IRestResponse response = client.Execute(request);

Not getting access_token by calling https://login.microsoftonline.com/{tenant}/oauth2/token

I want to get user email from user id (object identifier) from web api, but getting blank response while calling api for token. I am running this code from my Web API. Please help. Below is the code.
Given full permission to APIs
Getting Blank response in below line.
var responseBytes = await webClient.UploadValuesTaskAsync(url, "POST", requestParameters);
Below is code
var tenant = "tenant ID";
var clientID = "app ID";
// I've tried graph.microsoft.com and graph.microsoft.com/.default
var resource = "https://graph.microsoft.com";
var secret = "client secret";
string token;
using (var webClient = new WebClient())
{
var requestParameters = new NameValueCollection();
requestParameters.Add("scope", resource);
requestParameters.Add("client_id", clientID);
requestParameters.Add("grant_type", "client_credentials");
requestParameters.Add("client_secret", secret);
var url = "https://login.microsoftonline.com/{tenant}/oauth2/token";
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var responseBytes = await webClient.UploadValuesTaskAsync(url, "POST", requestParameters);
var responseBody = Encoding.UTF8.GetString(responseBytes);
var jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(responseBody);
token = jsonObject.Value<string>("access_token");
}
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var response = await client.GetAsync(new Uri("https://graph.microsoft.com/v1.0/user/" + ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")));
Your error is here:
requestParameters.Add("scope", resource);
It needs to be resource rather than scope:
requestParameters.Add("resource", resource);
Can you help me understand what documentation or tutorial you followed to make this mistake? I have seen it happen before and I am trying to understand the patterns here.
The documentation and authentication flow you should be following is here.

Time out error: HttpClient POST

I'm having trouble making POST using http client with Accept, ContentType and Authentication as headers. I tried several implementations using send aysnc and post async and all seemed to fail. I used https://www.hurl.it/ to make sure if it also was getting a time out error but it is working, getting back json data.
I get a connection time out error exception (in: var response = await client.SendAsync(request);) when running the below code.
Also I have curl command which i was trying to go off by, which is listed below as well.
Implementation:
// Body
var dictionary = new Dictionary<string, string>();
dictionary.Add("id", "123");
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("id", "123"));
// Http Client
var client = new HttpClient();
client.BaseAddress = new Uri("https://www.some_website.com/api/house");
// Http Request
var request = new HttpRequestMessage(HttpMethod.Post, "https://www.some_website.com/api/house");
// Accept
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Content-Type
//request.Content = new FormUrlEncodedContent(dictionary);
var httpContent = new StringContent(
JsonConvert.SerializeObject(
dictionary,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}),
Encoding.UTF8,
"application/json");
request.Content = new StringContent(
JsonConvert.SerializeObject(
dictionary,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}),
Encoding.UTF8,
"application/json");
// Authentication
var byteArray = new UTF8Encoding().GetBytes("user" + ":" + "pass");
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.Authorization = header;
// Communication
try
{
var response = await client.SendAsync(request);//PostAsync("https://www.some_website.com/api/house", httpContent);
if (response.IsSuccessStatusCode)
{
var myContent = await response.Content.ReadAsStringAsync();
var deliveryStatus = JsonConvert.DeserializeObject<MyOjbect>(myContent);
}
}
catch (Exception e)
{
//catch error
}
Curl:
curl -i --user user:123 -H Accept:application/json -H content-type:application/json -H cache-control:no-cache -X POST https://www.some_website.com/api/house -H Content-Type: application/json -d '{"id": "123"}'
You set your BaseAddress and the HttpRequestMessage Uri property both to the same absolute url, shouldn't it be the base address (ex. somewebsite.com) and the relative url (ex. (api/house). You can also inspect your request with Fiddler telerik.com/fiddler

How to Convert this curl to RestSharp

I have problem with converting this curl request to RestSharp it return 404 error, note the URL is correct.
I think the problem is come from -d parameter.
curl -v -X POST https://sandbox.bluesnap.com/services/2/transactions \
-H 'Content-Type: application/xml' \
-H 'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=' \
-d '
<card-transaction xmlns="http://ws.plimus.com">
<card-transaction-type>AUTH_CAPTURE</card-transaction-type>
<recurring-transaction>ECOMMERCE</recurring-transaction>
<soft-descriptor>DescTest</soft-descriptor>
<amount>11.00</amount>
<currency>USD</currency>
<card-holder-info>
<first-name>test first name</first-name>
<last-name>test last name</last-name>
</card-holder-info>
<credit-card>
<card-number>4263982640269299</card-number>
<security-code>837</security-code>
<expiration-month>02</expiration-month>
<expiration-year>2018</expiration-year>
</credit-card>
</card-transaction>'
I did some thing like this:
var client = new RestClient("https://sandbox.bluesnap.com/services/2/transactions");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "Content-Type: application/xml");
client.Authenticator = new HttpBasicAuthenticator("username", "password");
request.AddBody(GetXmlToSend(record, CriditCardInfo));
IRestResponse response = client.Execute(request);
var content = response.Content;
var response2 = client.Execute<dynamic>(request);
When you instantiate a new RestClient you should use the base url, e.g.:
var client = new RestClient("https://sandbox.bluesnap.com");
Then when you create the RestRequest you should be passing the path to the resource:
var request = new RestRequest("services/2/transactions", Method.POST);
write your xml data to a file, say file.xml
RestClient client = new RestClient(baseUrl);
RestRequest request = new RestRequest(remainingPartOfURL, Method.POST);
client.Authenticator = new HttpBasicAuthenticator(userId, password);
request.AddHeader("Content-Type", "application/xml");
request.AddHeader("Accept", "application/json");
request.AddFile("myFile", "D:\\file.xml");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
IRestResponse response = client.Execute(request);
if (response != null)
Console.WriteLine(response.Content);
IF you are invoking this code within Office environment then you need to provide proxy server info. You can get proxy server info from Settings->"Network and Internet"->Proxy
NetworkCredential aCredentials = new NetworkCredential();
aCredentials.Domain = "";
aCredentials.UserName = "";
aCredentials.Password = "";
WebProxy aProxy = new WebProxy();
aProxy.Address = new Uri("http://proxyserver.com:8080");
aProxy.Credentials = aCredentials;
client.Proxy = aProxy;

RestSharp - Authorization Header not coming across to WCF REST service

I am trying to call a locally hosted WCF REST service over HTTPS with basic auth.
This works and the Authorization header comes thru just fine and all is happy:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var request = (HttpWebRequest)WebRequest.Create("https://localhost/MyService/MyService.svc/");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add(
System.Net.HttpRequestHeader.Authorization,
"Basic " + this.EncodeBasicAuthenticationCredentials("UserA", "123"));
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
}
}
}
When I try to use RestSharp however, the Authorization header never comes thru on the request:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var credentials = this.EncodeBasicAuthenticationCredentials("UserA", "123");
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
var restRq = new RestSharp.RestRequest("/");
restRq.Method = Method.GET;
restRq.RootElement = "/";
restRq.AddHeader("Authorization", "Basic " + credentials);
var restRs = client.Execute(restRq);
What am i doing wrong with the RestSharp method?
I know that the AddHeader method works because this:
restRq.AddHeader("Rum", "And Coke");
will come thru, only "Authorization" seems stripped out/missing.
instead of adding the header 'manually' do the following:
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
client.Authenticator = new HttpBasicAuthenticator("UserA", "123");
I used milano's answer to get my REST service call to work (using GET)
Dim client2 As RestClient = New RestClient("https://api.clever.com")
Dim request2 As RestRequest = New RestRequest("me", Method.GET)
request2.AddParameter("Authorization", "Bearer " & j.access_token, ParameterType.HttpHeader)
Dim response2 As IRestResponse = client2.Execute(request2)
Response.Write("** " & response2.StatusCode & "|" & response2.Content & " **")
The key was making sure there was a space after the word 'Bearer' but this may apply to any type of custom token authorization header
You have to use ParameterType.HttpHeader parameter:
request.AddParameter("Authorization", "data", ParameterType.HttpHeader);
I was able to get the response from my rest API using this piece of code:
My API was returning server error and I used:
request.AddHeader("Authorization", $"Bearer {accessToken}");
var request = new RestRequest("/antiforgerytokensso", Method.Get);
restClient.Authenticator = new JwtAuthenticator(accessToken);
var response = await restClient.ExecuteAsync(request);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));

Categories

Resources