Using OAuth Security with REST

Documentation home

 

OAuth Techniques 1

1.       Authorization Code Grant 1

2.       Resource Owner Password Credentials Grant 2

3.       Client Credentials Grant 2

Steps to Use OAuth Security. 2

Additional OAuth Configuration Options 3

Scope. 3

Additional Authorization Parameters 3

Examples 3

Example 1 - Using Authorization Code Grant with the JavaScript API 3

Example 2 - Using Authorization Code Grant with a REST Web Service Resource. 4

Example 3 - Using Resource Owner Password Credentials Grant with the JavaScript API 5

Example 4 - Using Resource Owner Password Credentials Grant with a REST Web Service Resource  5

Example 5 - Using Client Credentials Grant with the JavaScript API 6

Example 6 - Using Client Credentials Grant with a REST Web Service Resource. 7

 

See also: REST Web Services overview, Using REST with the Programming API, REST Web Service Resources, Server Admin OAuth Configuration, OAuth Security Background Info

 

 

This document provides information and examples on using OAuth security with REST web services; this is only available from Javascript scripts.

 

OAuth Techniques

 

Within OAuth, there are three separate techniques:

 

1.     Authorization Code Grant

With this technique the user is required to authenticate by connecting to a 3rd party system such as Facebook or Google etc and entering a userid and password.

 

You are required to register your application with the 3rd party provider (step 1 below). The provider’s configuration requires specification of a redirect URL which is used by the provider to redirect the user after authentication. This redirect URL should be specified with the following format:

 

http://<ebase-hostname>:<ebase-port>/<ebase-webappname>/ufsreturn

 

e.g.

 

http://www.mydomain.com:3030/ebase/ufsreturn

 

The redirect URL will be resolved by the user’s browser. This means that during testing it is possible to use a host name of localhost or 127.0.0.1 or any other IP address or hostname that can be resolved.

 

2.     Resource Owner Password Credentials Grant

This technique does not require the user to login to the 3rd party provider to allow authorization. Instead the username and password are entered into an OAuth Configuration (step 2 below) and can also be specified dynamically at runtime either via configuration of a Web Services Resource using substitutable form fields, or set dynamically using the JavaScript API.

 

You are required to register your application with the 3rd party provider (step 1 below).

 

3.     Client Credentials Grant

This technique does not require the use of a username or password. It is usually used when asking for a resource where no user information is required or the client is also the resource owner.

 

You are required to register your application with the 3rd party provider (step 1 below).

 

 

Depending on the technique, the registration process will then provide you with some or all of the following information which is entered into an OAuth Configuration (step 2 below):

 

·         client id

·         secret key

·         authorization URL

·         token request URL

·         user name

·         password

 

Click here for more background information on OAuth techniques.

 

 

Steps to Use OAuth Security

 

1.      Register with the 3rd party provider (as above)

2.      Use the information provided by the registration to create an OAuth Configuration using the Server Administration Application

3.      Write a script statement to authenticate the user (Authorization Code Grant technique only) using the name of the OAuth Configuration created in the previous step e.g.

 

services.security.oauth.authorize("oauthconfigname");

 

You can also dynamically specify the scope with the Authorization Code Grant technique:

 

services.security.oauth.authorize("oauthconfigname", "newscope");

 

4.      Write script statements to call the web service e.g.

Using the Programming API:

 

var auth = HttpAuthentication.createOAuthAuthentication("oauthconfigname");

var response = services.rest.get(uri, auth);

 

To specify the scope, user name and password dynamically (this is only possible with the Resource Owner Password Credentials Grant technique):

 

   var auth = HttpAuthentication.createOAuthAuthentication("oauthconfigname", "private-read", "myusername", "mypassword");

var response = services.rest.get(uri, auth);

 

Using a REST Web Service Resource: the name of the OAuth Configuration is specified within the resource by clicking the Configure Rest Security icon  e.g.

 

resources.restResource1.call();

 

Note that if authentication fails in step 3, the error will be presented when the web service is called in step 4.

 

See the examples below for more details.

 

 

Additional OAuth Configuration Options

OAuth Configurations are created using the Server Administration Application. The following are optional parameters that may be required/configured depending on the REST endpoint.

 

Scope

Some endpoints require particular scope permissions such as read private data access or write access to an endpoint etc. The 3rd party provider will provide a list of scopes relevant for the application or endpoint. The scope can be specified in the OAuth Configuration created using the Server Administration Application or it can be specified dynamically at runtime either via configuration of a Web Services Resource using substitutable form fields, or set dynamically using the JavaScript API.

 

 

Additional Authorization Parameters

This allows configuration of extra request parameters that are added to the Authorization URL sent to the 3rd party provider.  An example of this might be to always prompt the user to login, so the 3rd party provider might require an additional parameter alwaysPromptLoginDialog=true

 

 

Examples

 

Example 1 - Using Authorization Code Grant with the JavaScript API Google provided service, request details passed as request parameters, returns a JSON string,

 

// First authenticate the user, authentication failures are signalled on the subsequent call to the web service

services.security.oauth.authorize("cbGoogle");

//

var auth = HttpAuthentication.createOAuthAuthentication("cbGoogle");       // Use the cbGoogle OAuth Configuration

var params = {

  part: "snippet ",

  home: "true "

};

// Call the web service

var response;

try

{

  response = services.rest.get("https://www.googleapis.com/youtube/v3/activities", null, params, auth);

}

catch (e)

{

  // catch connection or configuration or authentication failure

  event.owner.addErrorMessage(e);

}

// Process the response

if (response.isSuccess())

{

  ..

}

else

{

   // handle other errors e.g. not authorized to access requested data

}

 

Example 2 - Using Authorization Code Grant with a REST Web Service ResourceSpotify provided service; the response and responseStatusCode source fields are mapped to the response and responseStatusCode fields in the form. The resource returns a JSON string,

 

// First authenticate the user, authentication failures are signalled on the subsequent call to the web service

services.security.oauth.authorize("spotify");

//

var result;

try

{

  resources.getPlayLists.call();

  //response form field is mapped to the response source field in the REST Web Service Resource

  if (new java.lang.String(fields.responseStatusCode.value).startsWith("2"))

  {

    result = JSON.parse(fields.response.value);

  }

  else

  {

      // catch connection or configuration or authentication failure

      event.getOwner().addErrorMessage("Error loading user play list:" + fields.responseStatusCode.value);

  }

}

catch(e)

{

  event.getOwner().addErrorMessage("Error loading user play list: " + errorCode);

}

if (result)

{

  ..

}

 

Example 3 - Using Resource Owner Password Credentials Grant with the JavaScript APIbrentertainment.com demonstration service; setting the username and password dynamically at runtime. The response returns a JSON string.

 

// Use the spotifyClientCred OAuth configured as Resource Owner Password Credentials Grant type

var auth = HttpAuthentication.createOAuthAuthentication("brentertainment", null, "demouser", "testpass");      

 

// Call the web service

var response;

try

{

      var requestUri = "http://brentertainment.com/oauth2/lockdin/resource";

      var response = services.rest.get(requestUri, null, null, auth);

     

      if(response.isSuccess())

      {

        fields.code.value = response.code;

        fields.response.value = response.body;

      }

      else

      {

        //display an error message if an error

        event.getOwner().addErrorMessage("Error calling resource: " + response.code);

      }

}

catch (e)

{

   // catch connection, configuration failures

   var msg = "Error calling resource: " + e.errorCode;

   event.getOwner().addErrorMessage(msg);

}

 

 

Example 4 - Using Resource Owner Password Credentials Grant with a REST Web Service Resourcebrentertainment.com demonstration service; the request, username, password, response and responseStatusCode source fields are mapped to the request, response, username, password and responseStatusCode fields in the form. The resource returns a JSON string.

 

var result;

try

{

  fields.username.value = "demouser";

  fields.password.value = "testpass";

 

  resources.brentertainment.call();

 

  //response form field is mapped to the response source field in the REST Web Service Resource

  if (fields.responseStatusCode.value == "200")

  {

    result = JSON.parse(fields.response.value);

  }

  else

  {

      //display an error message if an error

            event.getOwner().addErrorMessage("Error calling resource: " + fields.responseStatusCode.value);

  }

}

catch(e)

{

      var msg = "Error calling resource: " + e.errorCode;

      event.getOwner().addErrorMessage(msg);

}

 

if(result)

{

  ..

}

 

 

Example 5 - Using Client Credentials Grant with the JavaScript APISpotify provided service to read current featured play lists in a particular country; the response returns a JSON string.

 

// Use the spotifyClientCred OAuth configured as Client Credentials Grant OAuth type

var auth = HttpAuthentication.createOAuthAuthentication("spotifyClientCred");      

 

// Call the web service

var response;

try

{    

  var params = {"country" : fields.country.value};

  var requestUri = "https://api.spotify.com/v1/browse/featured-playlists";

     

  var response = services.rest.get(requestUri, null, params, auth);

     

  if(response.isSuccess())

  {

    fields.responseStatusCode.value = response.code;

    fields.response.value = response.body;

  }

  else

  {

    //display an error message if an error

    event.getOwner().addErrorMessage("Error retrieving track list: " + response.code);

  }

}

catch (e)

{

  // catch connection, configuration failures

  event.owner.addErrorMessage(e);

}

if (response.isSuccess())

{

  ..

}

 

 

Example 6 - Using Client Credentials Grant with a REST Web Service ResourceSpotify provided service to read current featured play lists from a specified country; the country, response and responseStatusCode source fields are mapped to the country, response and responseStatusCode fields in the form. The resource returns a JSON string,

 

try

{    

  fields.country.value = "US"; //set to US country code

  resources.client_cred.call();

 

  //response form field is mapped to the response source field in the REST Web Service Resource

  if (fields.responseStatusCode.value == "200")

  {

    result = JSON.parse(fields.response.value);

  }

  else

  {

    //display an error message if an error

    event.getOwner().addErrorMessage("Error performing query: " + fields.responseStatusCode.value);

  }

}

catch (e)

{

  // catch connection, configuration failures

  event.owner.addErrorMessage(e);

}

 

if (response.isSuccess())

{

  ..

}