Drupal 7 Services 3.x Client with Authentication using Jquery

Hello folks.

Today I will share with you how to build a jQuery client to consume REST resources created with Drupal 7 & Services 3.x.

In the following example we will authenticate against drupal and after that get a specific user information.

1. Configure Services.

You must enable in your endpoint the resources for user and node. see image attached #2

Also you must enable authentication for your endpoint. see image attached #3

2. Configure jQuery.

You must validate your client have jQuery installed and also have cookie plugin available , just in case Cookie plugin is not available you can get from https://github.com/carhartl/jquery-cookie.

3. Create JQuery client.

we will assume the endpoint has path: /test

var username = 'admin';
var password =  'kickpass';

jQuery.ajax({
    url : "http://yourserver.com/test/user/login.json",
    type : 'post',
    data : 'username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password),
    dataType : 'json',
    error : function(data) {
        //error code
        //console.log(data);
    },
    success : function(data) {
        //success code
        var sessid = data.sessid;
        var session_name = data.session_name;
        //var user = data.user;       
        //console.log('session_name',session_name);
        //console.log('sessid',sessid);

        jQuery.cookie(session_name, sessid);
        
        jQuery.ajax({
            url : "http://yourserver.com/test/user/1.json",
            type : 'get',
            dataType : 'json',
            error : function(data) {
                //error code
                console.log('Error',data);
            },
            success : function(data) {
                //success code
                console.log('Cookie Accepted',data);
            }
        });
        
    }
});

This script has two stages.

Stage #1: Login against Drupal

Stage #2: If the authentication works, the return values is used to set a cookie

Stage #3: Request to Drupal to fetch information in JSON format for user id:1.

For sure you can improve this script to avoid storing user and password as plain text inside js code, also the cookie requires more effort to set it to the proper domain if you are running the script in a third party server.

Enjoy IT.

enzo.