Monday, 27 April 2015

How to implement Liferay Captcha in Custom Portlet

There are 3 simple steps to implement and verify/validate Liferay Captcha in your custom portlet

1) Declare taglibs in your JSP

2) Generate resourceURL which will return random number as a captcha

3) Verify captcha in your controller before executing business logic

Here are the detailed steps/code snippet with explanations

1) Declare taglibs in your JSP

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>

<portlet:defineObjects />

<%-- Liferay URL's for Action and Ajax --%>
<portlet:actionURL name="saveStudentDetails" var="saveStudentDetails" />
<portlet:resourceURL var="captchaURL" />

<aui:form action="<%= saveStudentDetails %>" method="post" name="fm">
    <input type="text" name="studentName" id="studentName" />
    <input type="submit" name="student" id="student" name="student" value="Save Student" /> &nbsp;
    <%-- Below line will show Image on the JSP --%>
    <liferay-ui:captcha url="<%=captchaURL%>" />

</aui:form>

2) Generate resourceURL which will return random number as a captcha

In above JSP we can see that we have used liferay's tag i.e. <liferay-ui:captcha url="<%=captchaURL%>" /> which will serve / show image to the user.

Here we can see that random image will be served via Liferay Ajax call i.e. <portlet:resourceURL var="captchaURL" />

3) Verify captcha in your controller before executing business logic

Inside controller there are two methods available
i) "serveResource" method which will simply return random number to the user via Ajax call
    //Here is a quick snippent:
   
    import com.liferay.portal.kernel.captcha.CaptchaUtil;

    @Override
    public void serveResource(ResourceRequest resourceRequest,
                ResourceResponse resourceResponse)
          throws  IOException, PortletException {

          try {
                CaptchaUtil.serveImage(resourceRequest, resourceResponse);
          }
          catch (Exception e) {
                System.out.println("An exception occured while serving captcha image");
          }
    }
ii) Validate user entered captcha on form submit
    Here is a quick snippent:
   
    public void saveStudentDetails(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {

System.out.println("Save student details");
try{
          CaptchaUtil.check(actionRequest);
          //This piece of code will be executed only if user entered data is correct for captch. If it is mis match it will throw "CaptchaException"
          }catch(CaptchaException e){
                System.out.println("User entered captcha miss match.");               
          }
}

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics   

No comments:

Post a Comment