Was this article helpful?

REST API with Gigya's Authorization Method

Last modified 05:44, 13 May 2014

This document is a guide for using Gigya's REST API with our proprietary access verification mechanism.

 

Note: Gigya offers a set of SDKs that provide wrap around Gigya's REST API. The SDKs make it simple to integrate Gigya's service for various development environments. Check out our SDKs documentation and find out if there is an SDK available for your preferred language. Otherwise, please continue with this guide and learn how to use our REST API directly.

 

Prerequisites for Using REST API Methods

Please make sure you comply with the following requirements prior to making a REST API method call:

  • Making API calls requires an API Key and a Secret Key which are obtained from the Dashboard page on the Gigya website. The Secret Key must be kept secret and never transmitted to an untrusted client or over insecure networks. The API Key is a required parameter in each REST API method. The Secret Key is used for signing requests

  • REST API method calls require an identified Gigya user (the identification of whom is performed using the UID parameter) with an active session. A user session is created when a user logs in or adds connection via the Gigya service. The only way to login / connect a user is through your client application, using our JavaScript API method calls: socialize.login, socialize.addConnection or socialize.notifyLogin. You may also use our ready made Plugins: Login Plugin or Add Connections Plugin.

REST-API_diagram.jpg

To learn more about our Social Login best practice integration, please refer to the Social Login Implementation guide.

Making an API Call

A Sample API Call:

The following is an example of an HTTP GET request:

http://socialize.gigya.com/socialize.setStatus?uid=<User ID>&apiKey=<Your APIKey>&nonce=<nonce>&
timestamp=<current unix-time>&sig=<signature>&status=Hello

The call is composed of the following elements:

  1. The Gigya REST API URL: 
    http://socialize.gigya.com/
     
  2. The method name, which, in the above example, would be: 
    socialize.setStatus
     
  3. Common required parameters (the following section explains this subject further):
    ?uid=<User ID>&apiKey=<Your APIKey>&nonce=<nonce>&timestamp=<current unix-time>&sig=<signature>
     
  4. Method-specific parameters. In the above example: 
    &status=Hello
Note: all parameter values should be in UTF-8 and URL-encoded.

 

Common Required Parameters

The following parameters are required for all API calls:

  • uid - The unique ID of a connected user, which this method call is associated with. This is the UID you received from Gigya after successful login of this user. Note: If you are using account linking then the UID would be your site user ID. To learn more about Social Sign-On with account linking (best practice), please refer to the Sign-On Implementation guide in the Developer's Guide.
  • apiKey - Your API application key. If you don't have one, please create one at the Dashboard page on the Gigya website.
  • timestamp - The current GMT time when the request is made. Follows the Unix time format (i.e. the number of seconds since Jan. 1st 1970). Requests that skew more than 120 seconds from the server time will be rejected.
  • nonce - A cryptographic nonce. The nonce string should be unique per method call.
  • sig - A signature verifying the authenticity of the request (see Signing the Request below for more details).
     

Making a Call Over HTTPS

When making the API call over HTTPS, you may pass the secret parameter. In such case the timestamp, nonce and sig parameters are no longer required.

Set the secret parameter with your Gigya Secret Key which can be obtained from the Dashboard page on the Gigya website.

The following is an example of an HTTPS request with the secret parameter:

https://socialize.gigya.com/socialize.setStatus?apiKey=<Your APIKey>&uid=<User ID>&secret=<Your Secret Key>&status=Hello

 

Note: Passing the secret parameter is allowed ONLY over HTTPS. If you attempt to pass the secret parameter over HTTP, the method will return the following error: "Secret Sent Over Http" (Error code: 403006).

 

Signing the Request

For security reasons, Gigya requires every API call to be signed, so as to guarantee that it originated from an authorized partner and was not tampered with in transit.

 

Please Note: We use a different algorithm for signing REST API requests and for signing API calls on client applications (JavaScript). This section discusses signing REST API requests. To learn how to sign the Gigya JavaScript API methods please refer to the Constructing a Signature section of the Developer's Guide.

 

The Authentication Flow

  1. Generate a nonce and a timestamp to be used on the call.
  2. Build a "Signature Base String" and use your Gigya Secret Key to sign it, as described in the Generating the Signature section below.
  3. When making the call - pass the nonce, the timestamp and the calculated signature as parameters to the API method (the nonce, timestamp and sig parameters).
  4. Gigya verifies that the timestamp on the call is within two minutes of the current time; if this is not the case, the call will be rejected.
  5. Gigya verifies that the nonce has not been used during the last 10 minutes; otherwise, the call will be rejected.
  6. Gigya verifies the signature by performing the same calculation, using the same Secret Key and comparing the result to the sig parameter.

 

Generating the Signature

To generate the signature, do the following:

 

REST-API_BaseString-narrow.gif

 

 

 

  • Apply the HMAC-SHA1 algorithm on the "Signature Base String" with your Gigya Secret Key as the key parameter of the algorithm as instructed in section 9.2 of the OAuth specifications.  Your Gigya Secret Key is provided, in BASE64 encoding, at the bottom of the Dashboard section on the Gigya website. This key should be kept on the server and should never be transmitted over any public network.
     
  • Base64-encode the signature.
     

 

 

You may use one of the OAuth libraries that can be found in http://oauth.net/code to build the Base String and generate the Signature.

Implementation Examples

Following are implementation examples in several languages:

 

<?php
require_once("OAuth.php");

// Signature calculation method
// The parameters for the signature calculation are:
//  1. Your secret key
//  2. The HTTP method ('GET' or 'POST')
//  3. Method API name (e.g. 'getUserInfo')
//  4. The parameters of the API method. Note that each API method has a different set of parameter.
function calcSignatureREST($secretKey, $httpMethod, $apiMethod, $parameters) {  
    $req = OAuthRequest::from_request($httpMethod,'http://socialize.gigya.com/socialize.'.$apiMethod, $parameters);
    $baseString = $req->get_signature_base_string();   
    return  base64_encode(hash_hmac('sha1', $baseString, base64_decode($secretKey), true));
}

$apiKey = "[ENTER YOUR API KEY HERE]";
// Your secret key (can be found at the bottom of the Site Setup page on the Gigya website)
$secretKey = "[ENTER YOUR SECRET KEY HERE]";

$timeStamp = time();
$nonce = $timeStamp . rand();

$apiMethod = "getUserInfo";
$uid = "[ENTER THE UID FOR A CONNECTED USER HERE]";

// The parameters for the socialize.getUserInfo API call:
$parameters = array(
    "apiKey" => $apiKey,
    "nonce" => $nonce,
    "timestamp" => $timeStamp,
    "uid" => $uid);

$signature = calcSignatureREST($secretKey, 'GET', $apiMethod, $parameters);

//Construct the URL and include the signature
$requestURL = "http://socialize.gigya.com/socialize." . $apiMethod . "?apiKey=" . urlencode($apiKey) . "&nonce=" . $nonce .
                "&sig=" . urlencode($signature) . "&timestamp=" . $timeStamp . "&uid=" . $uid;
               

//Check to see if libcurl is installed           
if (!function_exists('curl_init')){
    die("Sending this request requires PHP to be compiled with libcurl.");
}

//Now send the request
$ch = curl_init($requestURL);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo $response;

?>
Notes:
In order to make this code work in your environment, please:
  1. Click the "view source" icon (link located above code on the right hand side) - This will open a popup window with a text version of the code, which you may copy.
  2. Modify the value of the "secretKey" field in the code, to your Gigya secret key. Your secret key is provided at the bottom of the Dashboard page on Gigya's web-site.
  3. Note that the 4th parameter of the calcSignatureREST function is an array of the Gigya API method parameters. In this example we use the getUserInfo API method, thus the $parameters variable is initialized with the corresponding parameters. When changing the API method, change the list of parameters accordingly. Check the REST API Reference for the list of parameters for the required method call.
class Post
  #@Shmueli:
  # I am using here the hmac/sha1 lib you can find here http://rubyforge.org/projects/ruby-hmac/
  # user, id, status_message are instance methods of the Post class.
  # this authentication method only works for the status api call as the http parameters are ordered 
  # hard coded and not sorted automatically.
  # some modifications may be needed for other API calls.
  def authenticate_and_share
    #@ escape the status message and replace all + with %20 as spaces are CGI.escaped to +
    message_text = CGI.escape(status_message).gsub('+', '%20')
    user_id = user.id
  
    #@ here are the parameters you need to supply from your Gigya site's settings page.
    api_url = "http://socialize.gigya.com/socialize.setStatus"
    api_key = "HERE_GOES_YOUR_API_KEY"
    gigya_secret_key = "HERE_GOES_YOUR_GIGYA_SECRET_KEY"
  
    #@ decode secret key and prepare nonce.
    gigya_secret = Base64.decode64(gigya_secret_key)
    timestamp = Time.now.gmtime.to_i
    nonce = "#{user_id}#{id}#{timestamp}"
    http_method = "GET" #@shmu: define your HTTP method

    #@ parameters are ordered alphabetically, base string include HTTP method call and its parameters, 
    # all separated with unescaped "&"
    parameters = CGI.escape("apiKey=#{CGI.escape(api_key)}&nonce=#{CGI.escape(nonce)}&status=#{message_text}&
                    timestamp=#{timestamp}&uid=#{user_id}")
    base_string = "#{http_method}&#{CGI.escape(api_url)}&#{parameters}"
  
    #@ hmac/sha1 encription for the gigya secret and the base_string
    hmacsha1 = HMAC::SHA1.digest(gigya_secret, base_string)
    gigya_sign = Base64.encode64(hmacsha1).chomp.gsub(/\n/,'')
    gigya_sign = CGI.escape(gigya_sign) #@shmu: we must escape the signature as well.
  
    #@ finalized api request url with the signed signature
    request_url = "#{api_url}?apiKey=#{api_key}&nonce=#{nonce}&status=#{message_text}&timestamp=#{timestamp}
    &uid=#{user_id}&sig=#{gigya_sign}"
    puts request_url.inspect
  
    #@ read the response
    response_text = open(request_url).read
 
    #@ handle error messages from gigya XML output.
    regexp = /\<statusCode\>(.*?)\<\/statusCode\>/
    status_code = response_text.scan(regexp).to_s.to_i
    if status_code == 200
      okmsg = "Gigya: Content Shared: #{status_message} [#{user.nick}]"
      logger.info okmsg
      return okmsg
    else
      raise "GIGYA RESPONSE ERROR: #{response_text.scan(/\<errorMessage\>(.*?)\<\/errorMessage\>/).to_s} \n\n 
        #{response_text.inspect} \n\n\n [id:#{id}, user:#{user}]\n\nStatusMessage: #{status_message}\n\n Basestring:
        #{base_string}\n\n RequestURL: #{request_url}\n\n\n"
    end
  end
end

@The Ruby example code is written by Shmueli Ahdut.

Notes:
In order to make this code work in your environment, please:
  1. Click the "view source" icon (link located above code on the right hand side) - This will open a popup window with a text version of the code, which you may copy.
  2. Modify the value of the "secretKey" field in the code, to your Gigya Secret Key. Your secret key is provided at the bottom of the Dashboard page on Gigya's web-site.
  3. Note that the base string for calculating the signature include the Gigya API method name and the method's parameters. In this example we use the setStatus API method (see the api_url variable definition), thus the parameters variable is initialized with the corresponding parameters. When changing the API method, change the list of parameters accordingly. Check the REST API Reference for the list of parameters for the required method call.

 

The following code example is a Perl script that executes the socialize.getUserInfo API call: 

#!/usr/local/bin/perl

use Digest::HMAC_SHA1 qw(hmac_sha1);
use MIME::Base64;
use URI::Escape;

my $secretKey = "[ENTER YOUR SECRET KEY HERE]";
my $apikey = "[ENTER YOUR API KEY HERE]";
my $uid = "[ENTER THE UID FOR A CONNECTED USER HERE]";

my $key = MIME::Base64::decode ($secretKey);

my $time = time ();
my $nonce = $time;

my $url = "http://socialize.gigya.com/socialize.getUserInfo";
my $method = "GET";

my $parms = "apiKey=" . $apikey;
$parms .= "&nonce=" . $nonce;
$parms .= "&timestamp=" . $time;
$parms .= "&uid=" . uri_escape_utf8 ($uid);

my $sigbase = $method . "&" . uri_escape_utf8 ($url) . "&" . uri_escape_utf8 ($parms);

print STDERR "Base String: " . $sigbase . "\n\n";
my $hashed = hmac_sha1 ($sigbase, $key);
my $sig = MIME::Base64::encode ($hashed);
$sig =~ s/\n$//;

print STDERR "Sig: $sig\n";


my $url = "http://socialize.gigya.com/socialize.getUserInfo?apiKey=" . uri_escape ($apikey) . "&nonce=" . $time . "&sig=" . 
          uri_escape ($sig) . "&timestamp=" . $time . "&uid=" . uri_escape ($uid);

print STDERR "URL: " . $url . "\n";

 

Notes:
In order to make this code work in your environment, please:
  1. Click the "view source" icon (link located above code on the right hand side)  - This will open a popup window with a text version of the code, which you may copy.
  2. Modify the values of the "$secretKey" and the "$apikey" fields in the code, to your Gigya secret key and API-Key. Your Gigya keys are provided on the Dashboard page  on Gigya's web-site.
  3. Fill in the value of the UID of an logged-in user in the "$uid" field.
  4. Note that the "$parms" field is a concatenation of the Gigya API method parameters. In this example we use the getUserInfo API method, thus the "$parms" field consists of the getUserInfo parameters, sorted lexicographically. When changing the API method, change the list of parameters accordingly, and make sure to keep the parameters sorted. Check the REST API Reference for the list of parameters for the required method call.
  5. Run the script on a Linux host. The script prints a URL, which you may copy and paste into a browser window. This would list an XML formatted user information.

 

Authorization Parameters Overview

Each REST API request must contain identification and authorization parameters.

Note: the authorization parameters are required only if you are using the REST API directly. If you are using one of Gigya's SDKs then these parameters are not required, since the SDK implements the authorization method internally.

The set of required parameters is dependent on your selected method of authorization. There are two options:

  1. If you are conforming with the OAuth 2.0 standard, you will need to Pass an Access Token. For more information, please read the Using Gigya's REST API in compliance with OAuth 2.0 guide.
  2. If you are using Gigya's proprietary authorization method, you will need to pass the parameters specified here. Or, if you are making a call over HTTPS then you may pass the secret parameter instead of the timestampnonce and sig parameters. For more information, please read the Using Gigya's REST API with our proprietary authorization method guide.

 

Receiving Responses

After sending a REST request, you will receive a response, which is a JSON object.

Response JSON Example:

"socialize.removeConnectionResponse": 
  {
    "statusCode": 200,
    "errorCode": 0,
    "statusReason": "OK",
    "callId": "72fba4d7ff1041c180f0ea38f37dd24f"
  }

 

The name of the root element in the response consists of the name of the request API method with the word "Response" appended to it, as demonstrated in the example above: <socialize.removeConnectionResponse> (in the response for socialize.removeConnection method).

All responses include two child elements, <statusCode> and <statusReason>, which comply with the HTTP status and status reason:

  •      <statusCode> - This is the equivalent of the HTTP status code, such as 200, 400, 40, etc.
  •      <statusReason> - The equivalent of the HTTPreason code, such as "OK", "Bad Request", "Unauthorized", etc.

 

Some methods also return additional data as additional children of the root element. See the documentation of each method for details on the specific data it returns.

Note: A field that does not contain data, will not appear in the response.

Error Handling

If an error occurs, the response will include two additional child elements:

  •      <errorCode> - An application-specific error code. This value is used to distinguish between different causes for the same statusCode.
  •      <errorMessage> - A detailed textual error message designated for the purpose of logging during the process of debugging.

Response JSON with Error Example:

{
  "socialize.setStatusResponse":
    {
      "errorMessage": "Missing required parameter",
      "errorDetails": "Missing required parameter: uid",
      "statusCode": 400,
      "errorCode": 400002,
      "statusReason": "Bad Request",
      "callId": "dd1fc79e451b4dbbacefaf1072e91aff"
    }
}

The system will return HTTP status "200 OK" for all application-level errors and return the detailed error in the body of the response. Please note that some errors, such as 503, or "Server Unreachable" will still be returned on the HTTP level and should be handled accordingly.

Error Codes

For the complete list of error codes and descriptions, please refer to the Error Codes table.

 

Was this article helpful?
Pages that link here
Page statistics
24103 view(s) and 14 edit(s)
Social share
Share this page?

Tags

This page has no custom tags set.

Comments

You must to post a comment.

Attachments