Search code examples
restauthenticationheaderelgg

elgg api auth and user auth in header for REST?


hi I am new to elgg REST API.

I want to login and add post to wire for that I have method=wire.save_post I learned from Google that api auth and user auth must be given in request header how?

I am doing a ajax for adding post to wire :

$("#post_text").submit(function() {

$.ajax({
type:"POST",
url:"http://elgg.amusedcloud.com/services/api/rest/json/?",
data:{ method:'wire.save_post', text : text_val, access : 'public', wireMethod : 'site', username : uname },
dataType:"json",
success: function(data) {

}
});

});

Solution

  • Normally an ajax call to the elgg webservice you are referring to should look something like this. Note that the api_key and auth_token are part of the request URL.

    $("#post_text").submit(function() {
      $.ajax({
        type:"POST",
        url:"http://elgg.amusedcloud.com/services/api/rest/json/?method=wire.save_post&api_key=1140321cb56c71710c38feefdf72bc462938f59f&auth_token=df123dfgg455666",
        data:{
          text : text_val, 
          access : 'public', 
          wireMethod : 'site', 
          username : uname
        },
        dataType:"json",
        success: function(data) {
        }
      });
    });
    

    You didn't mention this but, when you say

    ... I learned from Google that api auth and user auth must be given in request header

    is this in the context of using OAuth as an authentication mechanism? In which case, you will have to use the HTTP header Authorization to send the hash and signature. The above call would then be like this.

    $("#post_text").submit(function() {
      $.ajax({
        type:"POST",
        url:"http://elgg.amusedcloud.com/services/api/rest/json/?method=wire.save_post&auth_token=df123dfgg455666",
        data:{
          text : text_val, 
          access : 'public', 
          wireMethod : 'site', 
          username : uname
        },
        beforeSend: function(xhr){
          xhr.setRequestHeader('X-Test-Header', 'test-value');
        },
        dataType:"json",
        success: function(data) {
        }
      });
    });
    

    Note the changes in the url and addition of beforeSend property to the ajax object.

    References:

    http://docs.elgg.org/wiki/OAuth

    http://api.jquery.com/jQuery.ajax/