Click here to Skip to main content
16,015,504 members
Articles / Web Development / ASP.NET

ASP.NET MVC - reCAPTCHA and Email Confirmation

Rate me:
Please Sign up or sign in to vote.
4.98/5 (60 votes)
25 Mar 2013Ms-PL4 min read 188.3K   5.5K   152   54
How to add reCAPTCHA and email confirmation to your ASP.NET MVC site.

Introduction

ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enable a clean separation of concerns and that gives you full control over markup for enjoyable, agile development.

ASP.NET MVC includes many features that enable fast, TDD-friendly development for creating sophisticated applications that use the latest web standards.

You can also choose an existing platform based on ASP.NET MVC from Microsoft Gallery, from:

  • Blogs
  • CMS
  • eCommerce
  • Forums
  • Galleries
  • Wiki
  • And more

But one thing that you probably need to add to any Web Application is BOTS Protection and Email Integrity.

So how can you prevent abuse from "bots", automated programs usually written to generate spam, and how to make sure the user has given you his real email address when registering on your Web Application?

The answer is: reCAPTCHA and Email Confirmation

reCAPTCHA

ASPNETMVCSecurity/1.png

A CAPTCHA is a program that can tell whether its user is a human or a computer. You've probably seen them — colorful images with distorted text at the bottom of Web registration forms. CAPTCHAs are used by many websites to prevent abuse from "bots," or automated programs usually written to generate spam. No computer program can read distorted text as well as humans can, so bots cannot navigate sites protected by CAPTCHAs.

Step 1: Download and Get reCAPTCHA Keys

First go to the reCAPTCHA site and register for a unique key, then Download reCAPTCHA .NET Library.

Save your Public and Private keys safely.

ASPNETMVCSecurity/2.png

Step 2: Create ASP.NET MVC 3 Web Application

Now, let’s start a new ASP.NET MVC 3 Web Application Project in Visual Studio 2010.

ASPNETMVCSecurity/3.png

Choose to create from “Internet Application” template

ASPNETMVCSecurity/4.png

Step 3: Recaptcha

Add the Recaptcha DLL as a reference to your project.

ASPNETMVCSecurity/5.png

Modify site Web.config with new keys under the appSettings section and add the keys we received before.

  • ReCaptchaPrivateKey
  • ReCaptchaPublicKey

ASPNETMVCSecurity/6.png

Step 4: Change Registration

Open the Controllers folder, open the AccountController file, and locate the Register method, add the new attribute:

C#
[RecaptchaControlMvc.CaptchaValidatorAttribute] 

ASPNETMVCSecurity/7.png

And add the reCAPTCHA logic to your registration code:

C#
[HttpPost]
[RecaptchaControlMvc.CaptchaValidatorAttribute]
public ActionResult Register(RegisterModel model, bool captchaValid)
{
    if (!captchaValid)
    {
        ModelState.AddModelError("", "You did not type the verification 
                                    word correctly. Please try again.");
    }
    else
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            MembershipCreateStatus createStatus;
            Membership.CreateUser(model.UserName, model.Password, 
                                  model.Email, null, null, true, null, 
                                  out createStatus);
 
            if (createStatus == MembershipCreateStatus.Success)
            {
                FormsAuthentication.SetAuthCookie(model.UserName, false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("",
                               ErrorCodeToString(createStatus));
            }
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}

Now place the following command in the Register.cshtml file:

C#
@Html.Raw(Html.GenerateCaptcha()) 

ASPNETMVCSecurity/8.png

Run your web site and enter the registration page, now you have to enter captcha before compiling the registration.

ASPNETMVCSecurity/9.png

Email Confirmation

In order to make sure the user has gave you his real email you need to use Email Confirmation mechanism to your site.

ASP MVC is doing some of the work for us, when a user is register to your site is assign with a unique ID (GUID) property called - ProviderUserKey

I’ll use this value to verify the account.

Step 1: Modify Web.Config with SMTP Settings

Before we get started with the Email Confirmation implementation we need to define our email settings, to do so I’ve used my Gmail account (just for this test) and add those values in the web.config just below the configuration tag.

XML
<configuration>
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network host="smtp.gmail.com" port="587" 
                                       userName="[YourName@Gmail.com]" 
                                       password="[Your Password]" />
      </smtp>
    </mailSettings>
  </system.net> 

Step 2: Add Confirmation View

After the user has register we want to redirect him to a confirmation page and tell him to check his email for the confirmation link, so:

Add a new View called – Confirmation

ASP.NET
 @{
    ViewBag.Title = "Email Confirmation";
}
<h2>
    Confirmation</h2>
<p>
    Thank you for registering. Please check your email for a confirmation
    request with a link that will confirm your account. Once you click the
    link, your registration will be complete.</p> 

In the AccountController add the result for confirmation.

C#
public ActionResult Confirmation()
{
    return View();
} 

Step 3: Send Mail

Before changing the registration we need to create the email functionality, this confirmation email will contain the ProviderUserKey and a direct link to our site.

The SendConfirmationEmail method will receive the UserName, and using Membership.GetUser we’ll be able to get all the information on that user and of course the ProviderUserKey.

I’ve built the confirmation URL using HttpContext and combined the User Guid ID and the site.

C#
 var verifyUrl = HttpContext.Current.Request.Url.GetLeftPart 
(UriPartial.Authority) + "/Account/Verify/" + confirmationGuid; 
public class EmailManager
{
    private const string EmailFrom = "noreplay@gmail.com";
    public static void SendConfirmationEmail(string userName)
    {
        var user = Membership.GetUser(userName.ToString());
        var confirmationGuid = user.ProviderUserKey.ToString();
        var verifyUrl = HttpContext.Current.Request.Url.GetLeftPart
           (UriPartial.Authority) + "/Account/Verify/" + confirmationGuid;
 
        using (var client = new SmtpClient())
        {
            using (var message = new MailMessage(EmailFrom, user.Email))
            {
                message.Subject = "Please Verify your Account";
                message.Body = "<html><head><meta content=\"text/html; 
                charset=utf-8\" /></head><body><p>Dear " + user.UserName +
                   ", </p><p>To verify your account, please click the following link:</p>"
                   + "<p><a href=\"" + verifyUrl + "\" target=\"_blank\">" + verifyUrl + "
                   +"</a></p><div>Best regards,</div><div>Someone</div><p>Do not forward "
                   +"this email. The verify link is private.</p></body></html>";
 
                message.IsBodyHtml = true;
                    
                client.EnableSsl = true;
                client.Send(message);
            };
        };
    }
} 

Step 4: Change Registration

Now we need to change the Registration functionality. The main thing is when creating a new user we need to change the user state to Not Approve and instead of performing login, we need to send him an email using our EmailManager and show him the confirmation page.

C#
[HttpPost]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        MembershipCreateStatus createStatus;
        //Make sure the user is not approve at this point!!!
        Membership.CreateUser(model.UserName, model.Password, model.Email,
        null, null, false, null, out createStatus);
 
        if (createStatus == MembershipCreateStatus.Success)
        {
            EmailManager.SendConfirmationEmail(model.UserName);
            return RedirectToAction("Confirmation", "Account");
        }
        else
        {
            ModelState.AddModelError("", ErrorCodeToString(createStatus));
        }
    }
 
    // If we got this far, something failed, redisplay form
    return View(model);
} 

Step 5: Add Verify

In AccountController I’ve added a Verify ActionResult. Verify will receive the User ID, then we’ll check for some bad IDs, if the user is already approved SignOut the user and redirect to the LogOn page, if the user is not approved, we need to change IsApprove to true and call UpdateUser to update the database with the new changes, also we will do the login for the user and redirect him to the home page.

C#
public ActionResult Verify(string id)
{
    if (string.IsNullOrEmpty(id) || (!Regex.IsMatch(id, @"[0-9a-f]{8}\-
                                     ([0-9a-f]{4}\-){3}[0-9a-f]{12}")))
    {
        ViewBag.Msg = "Not Good!!!";
        return View();
    }
 
    else
    {
        var user = Membership.GetUser(new Guid(id));
 
        if (!user.IsApproved)
        {
            user.IsApproved = true;
            Membership.UpdateUser(user);
            FormsAuthentication.SetAuthCookie(user.UserName, false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            FormsAuthentication.SignOut();
            ViewBag.Msg = "Account Already Approved";
            return RedirectToAction("LogOn");
        }
    }
} 

Links

Enjoy!

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Architect Sela
Israel Israel
Shai Raiten is VS ALM MVP, currently working for Sela Group as a ALM senior consultant and trainer specializes in Microsoft technologies especially Team System and .NET technology. He is currently consulting in various enterprises in Israel, planning and analysis Load and performance problems using Team System, building Team System customizations and adjusts ALM processes for enterprises. Shai is known as one of the top Team System experts in Israel. He conducts lectures and workshops for developers\QA and enterprises who want to specialize in Team System.

My Blog: http://blogs.microsoft.co.il/blogs/shair/

Comments and Discussions

 
GeneralRe: Useful Pin
Shai Raiten6-Feb-12 6:58
Shai Raiten6-Feb-12 6:58 
GeneralMy vote of 5 Pin
scott.leckie19-Jan-12 2:01
scott.leckie19-Jan-12 2:01 
GeneralRe: My vote of 5 Pin
Shai Raiten20-Jan-12 0:34
Shai Raiten20-Jan-12 0:34 
GeneralMy vote of 5 Pin
Kanasz Robert18-Jan-12 0:53
professionalKanasz Robert18-Jan-12 0:53 
GeneralRe: My vote of 5 Pin
Shai Raiten20-Jan-12 0:33
Shai Raiten20-Jan-12 0:33 
GeneralMy Vote of 5 Pin
thatraja17-Jan-12 23:45
professionalthatraja17-Jan-12 23:45 
GeneralRe: My Vote of 5 Pin
Shai Raiten17-Jan-12 23:49
Shai Raiten17-Jan-12 23:49 
GeneralMy vote of 5 Pin
_Tushar Patil17-Jan-12 18:49
_Tushar Patil17-Jan-12 18:49 
Very Helpful For Me Because I Am New In MVC....
GeneralRe: My vote of 5 Pin
Shai Raiten17-Jan-12 23:49
Shai Raiten17-Jan-12 23:49 
GeneralMy vote of 5 Pin
Rod Cullison17-Jan-12 1:50
Rod Cullison17-Jan-12 1:50 
GeneralRe: My vote of 5 Pin
Shai Raiten17-Jan-12 23:49
Shai Raiten17-Jan-12 23:49 
GeneralMy vote of 4 Pin
tonysawyer17-Jan-12 0:59
tonysawyer17-Jan-12 0:59 
GeneralRe: My vote of 4 Pin
Shai Raiten17-Jan-12 4:08
Shai Raiten17-Jan-12 4:08 
GeneralImpressive Representaion Pin
Sunasara Imdadhusen15-Jan-12 18:11
professionalSunasara Imdadhusen15-Jan-12 18:11 
GeneralRe: Impressive Representaion Pin
Shai Raiten15-Jan-12 19:22
Shai Raiten15-Jan-12 19:22 
GeneralMy vote of 5 Pin
TinTinTiTin12-Jan-12 0:45
TinTinTiTin12-Jan-12 0:45 
GeneralRe: My vote of 5 Pin
Shai Raiten12-Jan-12 2:10
Shai Raiten12-Jan-12 2:10 
QuestionVery neat article Pin
Sacha Barber11-Jan-12 23:31
Sacha Barber11-Jan-12 23:31 
AnswerRe: Very neat article Pin
Shai Raiten12-Jan-12 2:10
Shai Raiten12-Jan-12 2:10 
QuestionExcellent Pin
Prabu ram11-Jan-12 0:35
Prabu ram11-Jan-12 0:35 
AnswerRe: Excellent Pin
Shai Raiten11-Jan-12 0:38
Shai Raiten11-Jan-12 0:38 
GeneralMy vote of 5 Pin
Florian Rappl10-Jan-12 21:48
professionalFlorian Rappl10-Jan-12 21:48 
GeneralRe: My vote of 5 Pin
Shai Raiten10-Jan-12 23:04
Shai Raiten10-Jan-12 23:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.