Adsence750x90

Wednesday, August 13, 2014

How to create CAPTCHA in MVC 5


As a developer you probably aware of CAPTCHA, It is a type of challenge-response test used in computing to determine whether or not the user is human [CAPTCHA]
In development time we want to implement some CAPTCHA functionalists in your website, Lets check How can we do that



Basic idea is
  1. Create a image with some letters
  2. Save that letters in session or cache 
  3. Display our image in web page with textbox
  4. Validate TextBox value and letter what we saved in session
Then How to create an Image?

Function to create image
 
        /// <summary>
        /// Create image Byte[]
        /// </summary>
        /// <returns></returns>
        public byte[] DrawByte()
        {
            byte[] returnByte = { };
            Bitmap bitmapImage = new Bitmap(150, 30, PixelFormat.Format32bppArgb);

            //
            // Here we generate random string
            string key = getRandomString();
            
            //
            // key string adding to Session
            HttpContext.Current.Session.Add(SessionKey, key);

            //
            // Creating image with key
            using (Graphics g = Graphics.FromImage(bitmapImage))
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                Rectangle rect = new Rectangle(0, 0, 150, 30);
                HatchBrush hBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);
                g.FillRectangle(hBrush, rect);
                hBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.Red, Color.Black);
                float fontSize = 20;
                Font font = new Font(FontFamily.GenericSerif, fontSize, FontStyle.Strikeout);
                float x = 10;
                float y = 1;
                PointF fPoint = new PointF(x, y);
                g.DrawString(key, font, hBrush, fPoint);

                using (MemoryStream ms = new MemoryStream())
                {
                    bitmapImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    returnByte = ms.ToArray();
                }
            }
            return returnByte;
        }

Now we can chck the function to create session value or random string
        /// <summary>
        /// Generate random string value
        /// </summary>
        /// <returns></returns>
        private string getRandomString() {

            string returnString = string.Empty;
            string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

            Random rand = new Random();

            int length = rand.Next(5, 8);
            for (int i = 0; i < length; i++)
            {
                int pos = rand.Next(0, 62);
                returnString += letters[pos].ToString();
            }
            return returnString;
        }
Here I am usign one Controller to create Image.. check below for to see my Controller
namespace CaptchaMVC.Controllers
{
    public class CaptchaController : Controller
    {
        //
        // GET: /Captcha/
        public ActionResult Index()
        {
            CaptchaHelper captchaHelper = new CaptchaHelper();
            return File(captchaHelper.DrawByte(), "image/jpeg");
        }
 }
}
From the View you call
<div class="form-group">
            <span class="control-label col-md-2"></span>
                <div class="col-md-10">
                    <img src="@Url.Action("Index","Captcha")" alt="image" />
                </div>
        </div>
I this example I created a Person Controller and displaying and validating captcha image when someone create a new person. Here I am not including everything but you can download and check the whole code
//
        // POST: /Person/Create
        [HttpPost]
        public ActionResult Create(PersonViewModel person)
        {
            try
            {
                CaptchaHelper captchaHelper = new CaptchaHelper();
                bool success = captchaHelper.Verify(person.Captcha);
                if (success)
                { 
                    //captcha success
                }

                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
-- Happy Coding--
Download Sample

2 comments:

Unknown said...

Hello you are not the link des download enabled the file is not already the file you can send the file to my email orva..1980 @ yahoo.com.pe thank you very much

Unknown said...

Hello you are not the link des download enabled the file is not already the file you can send the file to my email orva..1980 @ yahoo.com.pe thank you very much