Monday, July 20, 2015

How to implement Captcha in ASP.NET MVC (C#.NET)

     Introduction


   CAPCTHA (Completely Automated Public Turing Test to tell Computers and Humans Apart) is used to protect website from machines accessing using automated scripts.  


 Pre-Requisites
       BotDetect CAPTCHA.


      Steps to Implement Captcha in Forgot Password page

Step 1: Create an MVC Project
              I.        Open Visual Studio 2012 and click on File->New->Project->Templates-Visual C#->Web->ASP.NET MVC 4 Web Application
            II.        Choose Location (your working folder ex: d:\samples) , give name as “Captcha” and click on OK button.


            III.        Choose Basic Template, Razor engine and click on OK
           IV.        Install BotDetect CAPTCHA from Visual Studio using Nuget packages. Right click on ‘Captcha’ solution and click on Manage NuGet  Packages
            V.        Click on Online->All and search for Captcha and choose BotDetect and click on Install

Step 2: Create a Model
              I.        Right click on Models folder, click on Add and click on Class
             II.        Name the class as “ForgotPasswordModel.cs” and create class as follows by importing namespace “System.ComponentModel.DataAnnotations

using System.ComponentModel.DataAnnotations;
public class ForgotPasswordModel
{

      [Required]
      [EmailAddress]
      [Display(Name="Enter your registered Email Address")]
      public string EmailId { get; set; }

      [Required]
      [Display(Name="Security Code")]
      public string SecurityCode { get; set; }
}
Step 3: Create a Controller
              I.        Right click on Controller, click on Add->Controller and name it as SamplesController and create an action “ForgotPassword” as follows
             II.        Import namespaces  ‘Captcha.Models’ and ‘BotDetect.Web.UI.Mvc’;
namespace Captcha.Controllers
{
      using Captcha.Models;
using BotDetect.Web.UI.Mvc;
public class SamplesController : Controller
    {

        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
//Following filter will validate security code
[CaptchaValidation("SecurityCode","Captcha","Incorrect Security Code")]        public ActionResult ForgotPassword(ForgotPasswordModel m)
        {
            if (ModelState.IsValid)
            {
                //here we need to write code to check whether email id exists in our database
                //Just for know I am checking whether given email id is equal to sateesh.gompa@gmail.com
                if (m.EmailId=="sateesh.gompa@gmail.com")
                    RedirectToAction("Thankyou");
                else
                    ModelState.AddModelError("NotFound","Email Address is not found in our database");

            }
            return View(m);

        }

}
            III.        Build the project
Step 4: Create a View
              I.        Right Click on action name “ForgotPassword” and click on Add View



             II.        turn on “Create a stongly-typed view’ checkbox,  Choose ForgotPasswordModel,  choose ‘Create’ in Scaffold Template and click on Add
            III.        ForgotPassword.cshtml page gets created in View->Samples folder.


           IV.        Import the namespace and include BotDetect styles inside BotDetectStyles section in view
@using BotDetect.Web.UI.Mvc
@section BotDetectStyles{
<link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl" type="text/css" rel="stylesheet" />
}

            V.        Add a div below security code in ForgotPassword.cshtml and  create capctha instance and pass it to captcha htmlhelper
<div>
@{MvcCaptcha captchaInstance=new MvcCaptcha("Captcha");}
@Html.Captcha(captchaInstance)
</div>
<div>
@Html.ValidationMessage("IVC")
</div>



Step 5: Define BotDetect Section in _Layout.cshtml

Open _Layout.cshtml file in Shared folder and put following line inside head tag @RenderSection("BotDetectStyles",false)

 Step 6: Exclude BotDetect paths from ASP.NET MVC Routing:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // BotDetect requests must not be routed
        routes.IgnoreRoute("{*botdetect}",  new { botdetect = @"(.*)BotDetectCaptcha\.ashx" });

….

}

       Press F5 and append “/samples/forgotpassword” to the url in browser to access the page.    


No comments:

Post a Comment