cancel
Showing results for 
Search instead for 
Did you mean: 

Using REST OAuth for Magento2 C#

Using REST OAuth for Magento2 C#

I wasn't sure what category to post this problem in.  I'm just getting started developing an application that communicates with a Magento2 website.

 

I am trying to get past Step 1 of my application which will be sending information to a Magento2 WebSite.  This is the code that I am using to attempt to authenticate my application to a Magento2 WebSite.  It is returning Unauthorized. 

 

I am not using a callback URL as this is not a web application, but rather a standalone console application that runs "hands off".

 

I already have an Access Token and an Access Token Secret and have tried generating the signature with or without those parameters but I still get "Unauthorized" when I send the command and try to get a response.

 

It seems like you should be able to go to the URL because you are requesting permission to go further and that it should not just throw an exception.  So I am doing something wrong and would greatly appreciate some help.  Thanks in advance. 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using Microsoft.Owin.Security.OAuth;
using OAuth;
using System.Web;
using System.Net;
using System.IO;
using System.Configuration;
using System.Security.Cryptography;

 

private void BeginAuthorization4(string MagentoServer, string ConsumerKey, string ConsumerSecret,
string AccessToken, string AccessTokenSecret)
{
string CallbackUrl = "http://localhost:8888";
var uri = new Uri(MagentoServer + "oauth/token/request");

OAuthBase oAuth = new OAuthBase();
string nonce = oAuth.GenerateNonce();
string timeStamp = oAuth.GenerateTimeStamp();
string parameters;
string normalizedUrl;
string signature = oAuth.GenerateSignature(uri, ConsumerKey, ConsumerSecret,
String.Empty, String.Empty, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out parameters);

 

StringBuilder sb = new StringBuilder("OAuth ");
sb.AppendFormat("oauth_callback=\"{0}\",", CallbackUrl);
sb.AppendFormat("oauth_consumer_key=\"{0}\",", ConsumerKey);
sb.AppendFormat("oauth_nonce=\"{0}\",", nonce);
sb.AppendFormat("oauth_signature_method=\"{0}\",", "HMAC-SHA1");
sb.AppendFormat("oauth_signature=\"{0}\",", signature);
sb.AppendFormat("oauth_timestamp=\"{0}\",", timeStamp);
sb.AppendFormat("oauth_version=\"{0}\"", "1.0");

 


var request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers[HttpRequestHeader.Authorization] = sb.ToString();
request.ContentType = "text/xml";
request.Accept = "text/xml";
request.KeepAlive = true;
request.Method = "POST";

try
{
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {

        Stream responseStream = response.GetResponseStream();
        StreamReader responseReader = new StreamReader(responseStream);
        string errorLabelText1 = responseReader.ReadToEnd();
    }

   else

   {
      string errorLabelText = "Status Code was: " + response.StatusCode.ToString();
   }

}
catch (WebException ex)
{
    var responseStream = ex.Response.GetResponseStream();
    StreamReader responseReader = new StreamReader(responseStream);
    string resp = responseReader.ReadToEnd();
    string errorLabelText2 = resp;
}

2 REPLIES 2

Re: Using REST OAuth for Magento2 C#

Hi,

 

Did you manage to get this resolved? Do you have the code for the oAuth class? I am using an oAuth class onlin.

 

Best Regards,

 

Ross

Re: Using REST OAuth for Magento2 C#

Getting Response as "Unauthorized". Using C# and used the HMAC-SHA1 algorithm to create the signature. The below is the code we used.

 

public string GenerateSignatureBase(Uri url, string consumerKey, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, string signatureType, out string normalizedUrl, out string normalizedRequestParameters)
{
if (token == null)
{
token = string.Empty;
}

if (tokenSecret == null)
{
tokenSecret = string.Empty;
}

if (string.IsNullOrEmpty(consumerKey))
{
throw new ArgumentNullException("consumerKey");
}

if (string.IsNullOrEmpty(httpMethod))
{
throw new ArgumentNullException("httpMethod");
}

if (string.IsNullOrEmpty(signatureType))
{
throw new ArgumentNullException("signatureType");
}

normalizedUrl = null;
normalizedRequestParameters = null;

List<QueryParameter> parameters = GetQueryParameters(url.Query);
parameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion));
parameters.Add(new QueryParameter(OAuthNonceKey, nonce));
parameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp));
parameters.Add(new QueryParameter(OAuthSignatureMethodKey, signatureType));
parameters.Add(new QueryParameter(OAuthConsumerKeyKey, consumerKey));
//parameters.Add(new QueryParameter(OAuthTokenKey, token));
if (!string.IsNullOrEmpty(token))
{
parameters.Add(new QueryParameter(OAuthTokenKey, token));
}

parameters.Sort(new QueryParameterComparer());

normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host);
if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
{
normalizedUrl += ":" + url.Port;
}
normalizedUrl += url.AbsolutePath;
normalizedRequestParameters = NormalizeRequestParameters(parameters);

StringBuilder signatureBase = new StringBuilder();
signatureBase.AppendFormat("{0}&", httpMethod.ToUpper());
signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));

return signatureBase.ToString();
}