Showing posts with label Authenticated Access required. Show all posts
Showing posts with label Authenticated Access required. Show all posts

Tuesday, March 10, 2015

Liferay JSON Web services Authenticated Access required

Whenever we are calling Liferay JSON web services we can find Authenticated Access required.
Even we send user name password still we can see the above exception. Generally this kind of exception we can when use apache http client to call Liferay JSON web services.

Generally this exception will encounter due to following reasons
  1. If the Liferay Web services not enable to Guest user Access
  2. When permission checker object is Null
  3. When users not sign in the permission checker  

The following is Liferay portal java class you can find the code



public class AuthenticatedAccessControlPolicy extends BaseAccessControlPolicy {

            @Override
            public void onServiceRemoteAccess(
                                    Method method, Object[] arguments,
                                    AccessControlled accessControlled)
                        throws SecurityException {

                        PermissionChecker permissionChecker =
                                    PermissionThreadLocal.getPermissionChecker();

                        if (!accessControlled.guestAccessEnabled() &&
                                    ((permissionChecker == null) || !permissionChecker.isSignedIn())) {

                                    throw new SecurityException("Authenticated access required");
                        }
            }

}

Even we use Admin User Name and Credentials to access these web services we can see Authenticated Access required.

Solution:

We need to use Basic Authorization heard in the URL request so that we can successfully call the Liferay JSON web services.

We need to set header to httpPost or HttpGet Request so that we can call these web services. When we set Authorization header basic then we need to encode credentials with Base64 encoding format

Example:


Base64 b = new Base64();
String encoding = b.encodeAsString(new String("test@liferay.com:test").getBytes());


Set Basic Authorization header to Http Post/Http Get request as follows


HttpPost post = new HttpPost("/LiferayJSONWebservices-portlet/api/jsonws/employee/get-employee");
Base64 b = new Base64();
String encoding = b.encodeAsString(new String("test@liferay.com:test").getBytes());
post.setHeader("Authorization", "Basic " + encoding);


Consume Liferay Plugin Portlet JSON web services Http Client


package com.meera.liferay;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
public class LiferayWebserviceClient {
     public static void main(String[] args) throws ClientProtocolException,
     IOException {
     ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
     HttpHost targetHost = new HttpHost("localhost", 8080, "http");
     DefaultHttpClient httpclient = new DefaultHttpClient();
     BasicHttpContext ctx = new BasicHttpContext();
     // Plugin Context Use for Liferay 6.1
     HttpPost post = new HttpPost("/LiferayJSONWebservices-portlet/api/jsonws/employee/get-employee");
     Base64 b = new Base64();
     String encoding = b.encodeAsString(new String("test@liferay.com:test").getBytes());
     post.setHeader("Authorization", "Basic " + encoding);
     List<NameValuePair> params = new ArrayList<NameValuePair>();
     params.add(new BasicNameValuePair("emplyeeId", "30722"));
     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
     post.setEntity(entity);
     HttpResponse resp = httpclient.execute(targetHost, post, ctx);
     resp.getEntity().writeTo(System.out);
     httpclient.getConnectionManager().shutdown();
     }

}

Consume Liferay Portal Services Using Http Client

package com.meera.liferay;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
public class LiferayWebserviceClient {
     public static void main(String[] args) throws ClientProtocolException, IOException {
           HttpHost targetHost = new HttpHost("localhost", 8080, "http");
           DefaultHttpClient httpclient = new DefaultHttpClient();
           BasicHttpContext ctx = new BasicHttpContext();
           // Plugin Context Use for Liferay 6.1
           HttpPost post = new HttpPost("/api/jsonws/country/get-countries");
           Base64 b = new Base64();
        String encoding = b.encodeAsString(new String("test@liferay.com:test").getBytes());
        post.setHeader("Authorization", "Basic " + encoding);
           List<NameValuePair> params = new ArrayList<NameValuePair>();
           //params.add(new BasicNameValuePair("emplyeeId", "30722"));
           UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
           post.setEntity(entity);
           HttpResponse resp = httpclient.execute(targetHost, post, ctx);
           resp.getEntity().writeTo(System.out);
           httpclient.getConnectionManager().shutdown();

     }

}

Required Jar Files


commons-codec.jar
httpclient.jar
httpcore.jar
commons-logging.jar


Download Example and Required Jar files


Monday, May 5, 2014

Consuming Liferay JSON Web Services

Introduction:

Liferay have provided JSON web services to expose data to outside world. We can use different client to call liferay web services

In this article we will see the following clients
  1. Java Client Consuming Liferay Web services
  2. Ajax Client Consuming Liferay Web services

The following are Articles which talk about Liferay JSON web services.

Liferay 6.2 and 6.1

Liferay 6.0.6

Note:

Read above all articles so that we will have good experience with Liferay JSON web services.

Java Client Consuming Liferay Web services

We can also use pure java client to call Liferay JSON web services. We will use Apache Http Client to call these web services.

Liferay also have implements Android SDK which used Apache Http Client to Liferay JSON web services.

Apache http client is set of java classes to call normal Http URLs in java code.

Some time we may need to call http URLs from java code such scenarios we will use Apache Http Client libraries.

Now we will call Liferay JSON web services Using Apache Http Client.

The following is place you can download required Apache Http Client Jar files


Assume following is your web service URL and have one parameter

The following is Liferay JSON web service URL



Using Plugin Context

http://localhost:8080/LiferayJSONWebservices-portlet/api/jsonws/
employee/get-employee?emplyeeId=1

Using Portal Context

http://localhost:8080/api/jsonws/LiferayJSONWebservices-portlet.employee/get-employee?emplyeeId=1



Note:


In Liferay 6.1 we have used Plugin Context in the URL from Liferay 6.2 we directly used Portal context

The following is HTTP java client


public static void main(String[] args) throws ClientProtocolException,
IOException {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HttpHost targetHost = new HttpHost("localhost", 8080, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("test@liferay.com", "test"));
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
BasicHttpContext ctx = new BasicHttpContext();
// ctx.setAttribute(ClientContext.AUTH_CACHE,authCache);
// Plugin Context Use for Liferay 6.1
HttpPost post = new HttpPost("/LiferayJSONWebservices-portlet/api/jsonws/employee/get-employee");
// Portal Context Use for Liferay 6.2
// HttpPost post = new HttpPost("/api/jsonws/LiferayJSONWebservices-portlet.employee/get-employee");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("emplyeeId", "30722"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(entity);
HttpResponse resp = httpclient.execute(targetHost, post, ctx);
resp.getEntity().writeTo(System.out);
httpclient.getConnectionManager().shutdown();
}


When you execute above code if you get Exception that Authenticated Access required then use following code


package com.meera.liferay;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
public class LiferayWebserviceClient {
     public static void main(String[] args) throws ClientProtocolException,
     IOException {
     ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
     HttpHost targetHost = new HttpHost("localhost", 8080, "http");
     DefaultHttpClient httpclient = new DefaultHttpClient();
     BasicHttpContext ctx = new BasicHttpContext();
     // Plugin Context Use for Liferay 6.1
     HttpPost post = new HttpPost("/LiferayJSONWebservices-portlet/api/jsonws/employee/get-employee");
     Base64 b = new Base64();
     String encoding = b.encodeAsString(new String("test@liferay.com:test").getBytes());
     post.setHeader("Authorization", "Basic " + encoding);
     List<NameValuePair> params = new ArrayList<NameValuePair>();
     params.add(new BasicNameValuePair("emplyeeId", "30722"));
     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
     post.setEntity(entity);
     HttpResponse resp = httpclient.execute(targetHost, post, ctx);
     resp.getEntity().writeTo(System.out);
     httpclient.getConnectionManager().shutdown();
     }

}



Note:

In the code I have used Plugin context bases on your choice you can use Plugin Context or Portal Context. If you are using Liferay 6.2 then you can use Portal context in the URL.


Calling Portal Services Using Http Client

package com.meera.liferay;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
public class LiferayWebserviceClient {
     public static void main(String[] args) throws ClientProtocolException, IOException {
           HttpHost targetHost = new HttpHost("localhost", 8080, "http");
           DefaultHttpClient httpclient = new DefaultHttpClient();
           BasicHttpContext ctx = new BasicHttpContext();
           // Plugin Context Use for Liferay 6.1
           HttpPost post = new HttpPost("/api/jsonws/country/get-countries");
           Base64 b = new Base64();
        String encoding = b.encodeAsString(new String("test@liferay.com:test").getBytes());
        post.setHeader("Authorization", "Basic " + encoding);
           List<NameValuePair> params = new ArrayList<NameValuePair>();
           //params.add(new BasicNameValuePair("emplyeeId", "30722"));
           UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
           post.setEntity(entity);
           HttpResponse resp = httpclient.execute(targetHost, post, ctx);
           resp.getEntity().writeTo(System.out);
           httpclient.getConnectionManager().shutdown();

     }

}

Required Jar Files


commons-codec.jar
httpclient.jar
httpcore.jar
commons-logging.jar


Download Example and Required Jar files


Ajax Client Consumer Liferay JSON Web services

The following is simple Ajax Program Call liferay web service with Basic Authorization Header
The following example uses the get Employee JSON Web Services of Plugin portlet and in the alert it will show employee name. This is just example

Here you need look into the part how to pass Authorization header in the request this is very important.

The following is Liferay JSON web service URL


Using Plugin Context

http://localhost:8080/LiferayJSONWebservices-portlet/api/jsonws/
employee/get-employee?emplyeeId=1

OR

http://localhost:8080/LiferayJSONWebservices-portlet/api/jsonws/employee/get-employee/employee-id/1

Using Portal Context

http://localhost:8080/api/jsonws/LiferayJSONWebservices-portlet.employee/get-employee?emplyeeId=1

OR

http://localhost:8080/api/jsonws/LiferayJSONWebservices-portlet.employee/get-employee /employee-id/1



.
Note:

In Liferay 6.1 we have used Plugin Context in the URL from Liferay 6.2 we directly used Portal context

Here we are passing Authorization header type basic and we will encode the user credentials.


<%@ include file="init.jsp"%>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).on('ready',function(){
            var username ="test@liferay.com";
            var password ="test"
            function make_base_auth(user, password) {
              var tok = user + ':' + password;
              var hash = btoa(tok);
              return "Basic " + hash;
            }
                $.ajax({
                  url: 'http://localhost:8080/LiferayJSONWebservices-portlet/api/jsonws/employee/get-employee/employee-id/1',
                  dataType: "json",
                  type: "get",
                  success: function(data){
                          alert(data.employeeName);
                  },
                  beforeSend: function(xhr){
                          xhr.setRequestHeader('Authorization',make_base_auth(username, password));
                                    },
                                    complete: function(){
                                    },
                  error: function(){
                  }
                });
             
 });
</script>

           
Passing Parameters Values in Ajax call


<%@ include file="init.jsp"%>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).on('ready',function(){
            var username ="test@liferay.com";
            var password ="test"
            function make_base_auth(user, password) {
              var tok = user + ':' + password;
              var hash = btoa(tok);
              return "Basic " + hash;
            }
                $.ajax({
                  url: 'http://localhost:8080/LiferayJSONWebservices-portlet/api/jsonws/ employee/get-employee',
                 data:{ emplyeeId:"1"}
                  dataType: "json",
                  type: "get",
                  success: function(data){
                          alert(data.employeeName);
                  },
                  beforeSend: function(xhr){
                          xhr.setRequestHeader('Authorization',make_base_auth(username, password));
                                    },
                                    complete: function(){
                                    },
                  error: function(){
                  }
                });
             
 });
</script>


Author

Recent Posts

Recent Posts Widget

Popular Posts