Installing Recaptcha. part 1

by Tomrel October 02, 2009 10:41

Look around my blog, you may notice something different about it. In my comments area i have installed a captcha. and in part one of this blog i'mma show u how to install it and get it working.

First of all you need to go to the Recaptcha website and sign up for an account. After that you want to register your website for a key. (or use a global key. i didn't try with the global key.) keep this key handy. you'll need it later.

lets jump into some code. first thing is first, open up your CommentView.aspx

I added this code above all the input boxes for the comments. I got the code from the recaptcha website here.

[code:html]
<script type="text/javascript">
        var RecaptchaOptions = {
            theme : "white"
            };
       </script>
    <script type="text/javascript" src="http://api.recaptcha.net/challenge?k=<Your Public Key>">
    </script>

    <noscript>
        <iframe src="http://api.recaptcha.net/noscript?k=&lt;Your Public Key>" 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>
[/code]


You remember those keys that I said to keep handy. well replace where it says <Your Public Key> above with.....wait for it....your public key.

now lets jump to the blog.js we are done here.

In this file there is a function called AddComment find that function and go to it. a few lines down into this function you will see several variables being declared. author, email, website, etc at the end of those add a couple of your own. Another thing I did was tack on a couple extra onto that string. that is sent as a callback function.

[code:js]

  var author = nameBox.value;
  var email = emailBox.value;
  var website = websiteBox.value;
  var country = countryDropDown ? countryDropDown.value : "";
  var content = contentBox.value;
  var notify = $("cbNotify").checked;
  var captcha = captchaField.value;
  var reChallenge = $("recaptcha_challenge_field").value;
  var reResponce = $("recaptcha_response_field").value;
 
  var callback = isPreview ? EndShowPreview : AppendComment;
  var argument = author + "-|-" + email + "-|-" + website + "-|-" + country + "-|-" + content + "-|-" + notify + "-|-" + isPreview + "-|-" + captcha + "-|-" + reChallenge + "-|-" + reResponce;
 

[/code]



If you are using blogengine 1.5 you want to use BlogEngine.$() rather then just $(). A couple things by adding the captcha to your page you get a hidden field called recaptcha_challenge_field and a text box called recaptcha_responce_field wich you want to get the values. The next thing I did was send them along with the others to the c# code behind.

so now we move onto the code behind open the  CommentsView.aspx.cs

You want to find a  function called RaiseCallbackEvent(string eventArgument). It'll be in the region called "ICallbackEventHandler Members." In here one of the first things that is done is we split the arguments back to the name, author.....etc etc. So one of the first things we shall do is get our captcha variables as well.


[code:c#]

if (!BlogSettings.Instance.IsCommentsEnabled)
            return;
    string[] args = eventArgument.Split(new string[] { "-|-" }, StringSplitOptions.None);
    string author = args[0];
    string email = args[1];
    string website = args[2];
    string country = args[3];
    string content = args[4];
    bool notify = bool.Parse(args[5]);
        bool isPreview = bool.Parse(args[6]);
        string sentCaptcha = args[7];
        string storedCaptcha = hfCaptcha.Value;
    string reChallenge = args[8];
    string reResponce = args[9];

[/code]



After we do that we can send it off to recaptcha.net to get verified. we accomplish this by sending web request via POST method. The response we get will signify if the captcha was verified or not.


[code:c#]

    //make sure there is something to test before we send.
    if (reResponce.Length > 0)
    {
        //the request we are sending
        WebRequest wr = WebRequest.Create("http://api-verify.recaptcha.net/verify");
        wr.ContentType = "application/x-www-form-urlencoded";
        wr.Method = "POST";
        //the paramaters (privatekey,remoteip,challenge,response)
        string reparam = "privatekey=<Your Private Key>" +
          "&remoteip=" + Request.UserHostAddress +
          "&challenge=" + reChallenge +
          "&response=" + reResponce;
        //turn them into bytes
        byte[] bytes = Encoding.ASCII.GetBytes(reparam);
        Stream os = null;
        wr.ContentLength = bytes.Length;
        os = wr.GetRequestStream();
        //write them to the requeststream
        os.Write(bytes, 0, bytes.Length);

        if (os != null)
        {
            //close the stream
            os.Close();
        }
       
        // get the response
        WebResponse webResponse = wr.GetResponse();
        //check if got response correctly
        if (webResponse == null)
        { return; }
        //read it as stream
        StreamReader sr = new StreamReader(webResponse.GetResponseStream());
        //first line will be true or false
        string strResponce = sr.ReadLine().Trim();
        if (strResponce.ToLower() == "false")
        {
            //false is not verified or error of some sort

            return;
        }
        //if it gets here it's verified
    }
    else
    {
        //nothing sent for captcha not worth progressing forward
        return;
    }

[/code]



Up there around the top of that block of code. there is a place for you to reference your keys and put your private key in. If it gets through here it will continue to post the comment.

 

At this point the code will block comments that the captcha doesn't verify. however it will still tell the user thanks for the comment. and in part 2 we will tackle how to fix that. see you in the next part.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

AJAX | ASP.net | BlogEngine

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen | Modified by Mooglegiant
Modified Again by Tomrel

About the AntiBlogger

I am a C# .net programmer. I also do some C++ and also pretty much anything. My programming interests include OpenGL, XNA, and what ever challenges me at the time.

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar