Salesforce Visualforce reCAPTCHA

Step by Step Procedure to Implement reCAPTCHA with Visualforce Page

Introduction

Salesforce web apps are developed and used from a long time through Visualforce platform. These apps can provide better functionality and performance, but at the same time are more prone to bot attack. Now to make secure these applications, one can use and implement following reCAPTCHA code in his Salesforce web app, which can enhance the security of Salesforce web app, by providing it a new and secured platform. Following is a step by step procedure with screenshot, to integrate reCAPTCHA with Salesforce web app.

Implementation Procedure:

Now the Salesforce user can make their app secure through the reCAPTCHA service of Google.reCAPTCHA is a free service from Google that helps protect websites from spam and abuse. A “CAPTCHA” is a test to tell human and bots apart. It is easy for humans to solve, but hard for “bots” and other malicious software to figure out. The Salesforce apps can be make secure through reCAPTCHA and can help the user to keep away their site from any bot.

In order to implement it with visualforce following steps, need to be followed by any Salesforce user:

Step 1:- Type recaptcha registration on Google search.

New Picture

Step 2:- Register with Recaptcha Site by using Gmail account.

New Picture

Step 3:- Once you login you will end up with this window.

recapcha3

Step 4:- Choose the type of reCaptcha select 1st Option as shown on fig.

recapcha4

Step 5:- Once you will choose type you have to accept the Recaptcha Term of Service select this checkbox and provide Domain which is your salesforce visualforce page url example:- realstatelightening-dev-ed–c.ap4.visual.force.com.Visualforce page url where you are showing this captcha.

And click on ‘Register’.

recapcha5

Step 6:- we can do two types of integration Client side and Server Side.In this blog we are doing Server Side Integration.Once we click on Server side integration we can see URL and secret (private key).

recapcha6

Step 7:- Click on Save changes.

recapcha7Step 8:- Now login your Salesforce Organisation https://login.salesforce.com/ and provide your credentials. Once you login go to >setup>Left Search bar> remote site setting or remote and select Security Controller > remote site settings.

recapcha8

Step 9:-Copy Url

recapcha9

Step 10:-Provide Remote site Name ‘captcha’. Remote site URl ‘Paste url which you have copied from recaptcha website’.

recapcha10

Write the Apex class:-

ApexClass:-

public class  Captcha
{
public boolean checkCurrentValue{get;set;
}
public String challenge{get;set;
}
public String response{get;set;
}
public String publicKey {get;set;
}
private static String privateKey = '6LcqayMUAAAAAJ4-c9Hnja3jGj3iKn_Bp-VsWQb1';// change this key to the key
// which we you have  generated after click on server side integration which is “secret”
private static String baseUrl = ‘https://www.google.com/recaptcha/api/verify’;
    public String myName { get; set; }
    public String myEmail { get; set; }
    public Boolean verified { get; private set; }
    public Captcha()
    {
        publicKey = ‘6LcqayMUAAAAAO3g81Dlwb6jjLmahE0gurJyy7zv’;
// we can get this key when we click on client site integration with
 “data-sitekey=”6LcqayMUAAAAAO3g81Dlwb6jjLmahE0gurJyy7zv”
        this.verified = false; checkCurrentValue=false;
  challenge = ApexPages.currentPage().getParameters().get(‘recaptcha_challenge_field’);
  response =  ApexPages.currentPage().getParameters().get(‘recaptcha_response_field’);
    }
    public PageReference verify()
    {
        System.debug(‘reCAPTCHA verification attempt’);
        // On first page load, form is empty, so no request to make yet
        if ( challenge == null || response == null )
        {
            System.debug(‘reCAPTCHA verification attempt with empty form’);
            return null;
        }
        HttpResponse r = makeRequest(baseUrl,’privatekey=’ + privateKey + ‘&remoteip=’  + remoteHost + ‘&challenge=’ + challenge + ‘&response=’  + response);
        if ( r!= null )
        {
            this.verified = (r.getBody().startsWithIgnoreCase(‘true’));
        }
        if(this.verified)
        {
            // If they pass verification, you might do something interesting here
            // Or simply return a PageReference to the “next” page
            return null;
        }
        else
        {
            // stay on page to re-try reCAPTCHA
            return null;
        }
    }
    public PageReference reset()
    {
        return null;
    }  
    /* Helper methods */
    private static HttpResponse makeRequest(string url, string body) 
    {
        HttpResponse response = null;
        HttpRequest req = new HttpRequest();  
        req.setEndpoint(url); req.setMethod(‘POST’); req.setBody (body);
        try
        {
            Http http = new Http();
            response = http.send(req);
            System.debug(‘reCAPTCHA response: ‘ + response);
            System.debug(‘reCAPTCHA body: ‘ + response.getBody());
        }
        catch(System.Exception e)
        {
            System.debug(‘ERROR: ‘ + e);
        }
        return response;
    }
    private String remoteHost
    {
        get {
            String ret = ‘127.0.0.1’;
            // also could use x-original-remote-host
            Map<String, String> hdrs = ApexPages.currentPage().getHeaders();
            if (hdrs.get(‘x-original-remote-addr’)!= null)
                ret =  hdrs.get(‘x-original-remote-addr’);
            else if (hdrs.get(‘X-Salesforce-SIP’)!= null)
                ret =  hdrs.get(‘X-Salesforce-SIP’);
            return ret;
        }
    } 
}

Step 11:- Create Visualforce Page with Name TestCaptcha copy paste visualforce page code.

ApexClass:-

public class  Captcha
 {
    public boolean checkCurrentValue{get;set;}
    public String challenge{get;set;}
    public String response{get;set;}
    public String publicKey {get;set;}
    private static String privateKey = ‘6LcqayMUAAAAAJ4-c9Hnja3jGj3iKn_Bp-VsWQb1’;// change this key to the key
 which we you have  generated after click on server side integration which is “secret”
    private static String baseUrl = ‘https://www.google.com/recaptcha/api/verify’;
    public String myName { get; set; }
    public String myEmail { get; set; }
    public Boolean verified { get; private set; }
    public Captcha()
    {
        publicKey = ‘6LcqayMUAAAAAO3g81Dlwb6jjLmahE0gurJyy7zv’;
// we can get this key when we click on client site integration with
 “data-sitekey=”6LcqayMUAAAAAO3g81Dlwb6jjLmahE0gurJyy7zv”
        this.verified = false;
        checkCurrentValue=false;
        challenge = ApexPages.currentPage().getParameters().get(‘recaptcha_challenge_field’);
        response =  ApexPages.currentPage().getParameters().get(‘recaptcha_response_field’);
    }
    public PageReference verify()
    {
        System.debug(‘reCAPTCHA verification attempt’);
        // On first page load, form is empty, so no request to make yet
        if ( challenge == null || response == null )
        {
            System.debug(‘reCAPTCHA verification attempt with empty form’);
            return null;
        }
        HttpResponse r = makeRequest(baseUrl,’privatekey=’ + privateKey + ‘&remoteip=’  + remoteHost + ‘&challenge=’ + challenge + ‘&response=’  + response);
        if ( r!= null )
        {
            this.verified = (r.getBody().startsWithIgnoreCase(‘true’));
        }
        if(this.verified)
        {
            // If they pass verification, you might do something interesting here
            // Or simply return a PageReference to the “next” page
            return null;
        }
        else
        {
            // stay on page to re-try reCAPTCHA
            return null;
        }
    }
    public PageReference reset()
    {
        return null;
    }  
    /* Helper methods */
    private static HttpResponse makeRequest(string url, string body) 
    {
        HttpResponse response = null;
        HttpRequest req = new HttpRequest();  
        req.setEndpoint(url);
        req.setMethod(‘POST’);
        req.setBody (body);
        try
        {
            Http http = new Http();
            response = http.send(req);
            System.debug(‘reCAPTCHA response: ‘ + response);
            System.debug(‘reCAPTCHA body: ‘ + response.getBody());
        }
        catch(System.Exception e)
        {
            System.debug(‘ERROR: ‘ + e);
        }
        return response;
    }
    private String remoteHost
    {
        get {
            String ret = ‘127.0.0.1’;
            // also could use x-original-remote-host
            Map<String, String> hdrs = ApexPages.currentPage().getHeaders();
            if (hdrs.get(‘x-original-remote-addr’)!= null)
                ret =  hdrs.get(‘x-original-remote-addr’);
            else if (hdrs.get(‘X-Salesforce-SIP’)!= null)
                ret =  hdrs.get(‘X-Salesforce-SIP’);
            return ret;
        }
    } 
}

Step 11:- Create Visualforce Page with Name TestCaptcha copy paste visualforce page code.

VisualForce Page:-

<apex:page controller=”CaptchaCtr” cache=”false”>
<apex:pageBlock title=”Captcha Verification”>
<apex:form >
<apex:pageBlockSection columns=”1″>
<apex:pageBlockSectionItem >
<apex:outputLabel for=”inputName” value=”Name”/>
<apex:inputText value=”{!myName}” id=”inputName”/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel for=”inputEmail” value=”Email”/>
<apex:inputText value=”{!myEmail}” id=”inputEmail”/>
</apex:pageBlockSectionItem>
<!– Show the reCAPTCHA form if they are not yet verified –>
<apex:pageBlockSectionItem rendered=”{! NOT(verified)}”>
<!– reCAPTCHA verification Source: https://developers.google.com/recaptcha/docs/display –>
<script type=”text/javascript” src=”https://www.google.com/recaptcha/api/challenge?k={!publicKey}”>
</script>
<noscript>
<iframe src=”https://www.google.com/recaptcha/api/noscript?k={!publicKey}” height=”300″ width=”500″ frameborder=”0″>
</iframe><br/>
<textarea name=”recaptcha_challenge_field” rows=”3″ cols=”40″></textarea>
<input type=”hidden” name=”recaptcha_response_field” value=”manual_challenge”/>
</noscript>
<!– end reCAPTCHA verification –>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:commandButton action=”{!verify}” value=”Check If I’m Human” rendered=”{! NOT(verified)}”/>
</apex:pageBlockSectionItem>
<!– Otherwise, they are verified, show a confirmation message –>
<apex:pageBlockSectionItem rendered=”{!verified}”>
<p>reCAPTCHA verification suggests that you’re not a ‘bot.</p>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:form>
</apex:pageBlock>
</apex:page>

Step 12:-Now we can see the recaptcha on visualforce page with Name and Email field..

recapcha12

Step 13:- To verify recaptcha type the Challenge in input field provided in the form of image as shown in snap.

recapcha13

Step 14:- Once we provide the correct challenge the response we will receive ‘recaptcha verification suggest that you’re not a bot’.’

recapcha14

Conclusion: reCAPTCHA app is especially designed for Salesforce web platform users and can enhance the security feature of Salesforce web applications. Any Salesforce developer can use the above step by step listed procedure in order to provide an interactive and secure platform to its users. It can easily differentiate between Bot and humans.

Learn more at Salesforce App Development Company/

1 Comment
  1. Subramanyam R 2 months ago

    then what suppose if i want to move to some other sandbox..we are hardcoded the url in the google api then for other sandbox again i have to change the Salesforce visualforce base URL???

Leave a Reply

CONTACT US

We're not around right now. But you can send us an email and we'll get back to you, asap.

Sending
Property of Forcetalks.com
Copyright 2017 Forcetalks. All Right Reserved.

Log in with your credentials

or    

Forgot your details?