Oauth signature examples

From Gvp-public
Jump to navigation Jump to search

This page provides some examples in different languages on how to add OAuth signature to the UNIAPI requests.

It is important to notice that OAuth Signature uses current timestamp for signing the requests. This forces devices to be synchronized with API servers with a small margin allowed. If a device gets an invalid timestamp error (see StatusCode for more information), it should make use of the GetTime method, that will return the current server time. This method can be called without OAuth signature to allow devices to sync clocks.


Javascript

In http://oauth.net/code/ you can find the latest version of oauth.js and sha1.js libraries, used in this code snippet.

var signedUrl = OAuth.generateOAuthSignedURL("GET", url, params, sConsumerKey, sConsumerSecret);

...

generateOAuthSignedURL : function (httpMethod, serviceURL, parameters, consumerKey, consumerSecret) {
	var timestamp = OAuth.timestamp();
	var nonce = OAuth.nonce(11);
	var tokenSecret = "";
	var message = null;
	var accessor = {consumerSecret: consumerSecret, tokenSecret: tokenSecret};
	var normalizedParameters, signature, resultURL, authorizationHeader;

	//Ponemos este If porque en POST no se mandan los parámetros en las cabeceras HTTP.
	//Por eso hacemos esta distinción
	if ((Utils.isArray(parameters) && parameters.length === 0) || httpMethod === "POST") {
		message = { method: httpMethod,
			action: serviceURL,
			parameters: OAuth.decodeForm('')
		};
	}else {
		message = { method: httpMethod,
			action: serviceURL,
			parameters: OAuth.getParameterList(parameters)
		};
	}
	message.parameters.push(["oauth_version", "1.0"]);
	message.parameters.push(["oauth_consumer_key", consumerKey]);
	//message.parameters.push(["oauth_token", ""]);
	message.parameters.push(["oauth_timestamp", timestamp]);
	message.parameters.push(["oauth_nonce", nonce]);
	message.parameters.push(["oauth_signature_method", "HMAC-SHA1"]);
	OAuth.SignatureMethod.sign(message, accessor);

	normalizedParameters = OAuth.SignatureMethod.normalizeParameters(message.parameters);
	//var signatureBaseString = OAuth.SignatureMethod.getBaseString(message);

	signature = OAuth.percentEncode(OAuth.getParameter(message.parameters, "oauth_signature"));
	resultURL = serviceURL + "?" + normalizedParameters + "&oauth_signature=" + signature;
	authorizationHeader = OAuth.getAuthorizationHeader("", message.parameters);
	return resultURL;
}


C#

In http://oauth.net/code/ you can find the latest version of OAuth libraries used in this code snippet.

public void GetRequest(string serviceName, string methodName, Dictionary<string, string> parameters, bool usePost, out string requestMethod, out string requestUrl, out string requestParameters)
{
    // Request Method
    requestMethod = usePost ? "POST" : "GET";

    // Request Url
    requestUrl = this.serviceRootUrl + "/" + serviceName + "/" + methodName;

    // Request Parameters
    Dictionary<string, string> requestParameterList = new Dictionary<string, string>(parameters);

    // Consumer key must always be present
    requestParameterList.Add("oauth_consumer_key", this.consumerKey);

    if (this.alwaysSendIpAddress)
    {
        if (!requestParameterList.Select(s => s.Key.ToLower()).Contains("ipaddress"))
        {
            requestParameterList.Add("ipaddress", this.GetIpAddress());
        }
    }

    if (this.useSignature)
    {
        // Adds signature parameters to the hashtable
        requestParameterList.Add("oauth_nonce", Environment.TickCount.ToString());
        requestParameterList.Add("oauth_signature_method", "HMAC-SHA1");
        requestParameterList.Add("oauth_timestamp", MibUnixTime.ToUnixTime(DateTime.Now).ToString());
        requestParameterList.Add("oauth_version", "1.0");
        requestParameterList.Add("oauth_signature", new OAuthSigner(this.consumerSecret).GenerateSignature(new OAuthRequest(requestUrl.ToString(), requestParameterList, requestMethod)));
    }

    // Request data
    List<string> items = new List<string>();
    foreach (KeyValuePair<string, string> kvp in requestParameterList)
    {
        items.Add(string.Concat(kvp.Key, "=", System.Web.HttpUtility.UrlEncode(kvp.Value)));
    }
    requestParameters = string.Join("&", items.ToArray());
}