Recaptcha in User Registration

Topics: ASP.NET 2.0, Business Logic Layer, Controls
Apr 6, 2013 at 2:10 PM
I'm trying to incorporate recaptcha into the user registration process as I want to allow self-registration without a million bots signing up. However, I'm experiencing no joy. I've tried modeling this after the contact form, but I clearly don't know what I'm doing. Can anyone offer any insight into how I would do this? I'm using BE2.7.
Apr 7, 2013 at 4:25 PM
I figured this out if anyone is interested. I found some examples (specific to the createuserwizard) on the net and then monkeyed around with it until I got it together. I wanted to integrate it well enough to use the recaptcha stuff that is already in BE, but it's not fully integrated to disappear when you disable recaptcha in the admin panel. (I could also never get captcha to equal null, so I commented that 'else if' statement out...maybe go back to it later.)

So, in your register.aspx, just use the same control from the contact form:
<blog:RecaptchaControl ID="recaptcha" runat="server" TabIndex="9" />
Then in your register.aspx.cs replace your RegisterUser_CreatingUser with:
protected void RegisterUser_CreatingUser(object sender, LoginCancelEventArgs e)
        {
            App_Code.Controls.RecaptchaControl captcha = (App_Code.Controls.RecaptchaControl)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("recaptcha") as App_Code.Controls.RecaptchaControl;
            captcha.Validate();
            if (Membership.GetUser(this.RegisterUser.UserName) != null)
            {
                e.Cancel = true;
                this.Master.SetStatus("warning", "Please select another user name.");
            }
            else if (Membership.GetUserNameByEmail(this.RegisterUser.Email) != null)
            {
                e.Cancel = true;
                this.Master.SetStatus("warning", "Please select another email address.");
            }
            //else if (captcha == null)
            //{
            //  e.Cancel = true;
            //  this.Master.SetStatus("warning", "Captcha Phrase is required.");
                //return;
            //}
            else if (!captcha.IsValid)
            {
                e.Cancel = true;
                this.Master.SetStatus("warning", "Captcha Phrase was typed incorrectly.");
            }
Jun 28, 2013 at 7:28 AM
Nice :)
I've just switched to BE.NET 2.8, but it looks like I might need this soon. Until recently bots were not hitting the registration page at all, but that seems to have changed now.
Coordinator
Jun 28, 2013 at 4:25 PM
I haven't got any spam for months after Google made changes to algorithm and start punish spammers. Even got emails asking to remove spam I didn't notice, because SEO ratings for these guys went down. But last few weeks it seems "back to normal", with few dozens killed by Akismet daily. Not sure if Google dropped it or they found a way to cheat the system.
Aug 10, 2013 at 9:25 PM
Lately I'm getting several hundred comment spams per day... and that's with reCAPTCHA enabled. Akismet filters most of them out, but it makes my database fill up with junk. Just removing them every couple of days takes quite some time as BlogEngine is slow at deleting and purging them :(
Oct 22, 2013 at 9:36 PM
Edited Oct 22, 2013 at 9:44 PM
Thorarin, how do you get it to work on the user creation page?
I have the javascript code in there (copied from the commenting section), Im sure I have to do something to the CS file, but not sure what.

Thanks

This is code in my register.aspx.cs file:
namespace Account
{
    using System;
    using System.Web.Security;
    using System.Web.UI.WebControls;
    using System.Linq;
    using BlogEngine.Core;
    using Resources;

    using Page = System.Web.UI.Page;
    using System.Web.UI.HtmlControls;

    /// <summary>
    /// The account register.
    /// </summary>
    public partial class Register : Page
    {
        #region Methods

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (BlogSettings.Instance.CreateBlogOnSelfRegistration && Blog.CurrentInstance.IsPrimary)
            {
                Response.Redirect("create-blog.aspx");
            }
            HtmlAnchor HeadLoginStatus = RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("HeadLoginStatus") as HtmlAnchor;
            if (HeadLoginStatus != null)
            {
                HeadLoginStatus.HRef = Utils.RelativeWebRoot + "Account/login.aspx";
            }

            this.RegisterUser.ContinueDestinationPageUrl = this.Request.QueryString["ReturnUrl"];
            this.hdnPassLength.Value = Membership.MinRequiredPasswordLength.ToString();

            // if self registration not allowed and user is trying to directly
            // navigate to register page, redirect to login
            if (!BlogSettings.Instance.EnableSelfRegistration)
            {
                Response.Redirect(Utils.RelativeWebRoot + "Account/login.aspx");
            }
        }

        /// <summary>
        /// Handles the CreatedUser event of the RegisterUser control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void RegisterUser_CreatedUser(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(BlogSettings.Instance.SelfRegistrationInitialRole))
            {
                string role = Roles.GetAllRoles().FirstOrDefault(r => r.Equals(BlogSettings.Instance.SelfRegistrationInitialRole, StringComparison.OrdinalIgnoreCase));
                if (!string.IsNullOrEmpty(role))
                {
                    Roles.AddUsersToRoles(new string[] { this.RegisterUser.UserName }, new string[] { role });
                }
            }

            Security.AuthenticateUser(this.RegisterUser.UserName, this.RegisterUser.Password, false);

            FormsAuthentication.SetAuthCookie(this.RegisterUser.UserName, false /* createPersistentCookie */);

            var continueUrl = this.RegisterUser.ContinueDestinationPageUrl;
            if (String.IsNullOrEmpty(continueUrl))
            {
                continueUrl = Utils.RelativeWebRoot;
            }

            this.Response.Redirect(continueUrl);
        }

        /// <summary>
        /// Handles the CreatingUser event of the RegisterUser control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.LoginCancelEventArgs"/> instance containing the event data.</param>
        protected void RegisterUser_CreatingUser(object sender, LoginCancelEventArgs e)
        {
            if (Membership.GetUser(this.RegisterUser.UserName) != null)
            {
                e.Cancel = true;
                this.Master.SetStatus("warning", Resources.labels.anotherUserName);
            }
            else if (Membership.GetUserNameByEmail(this.RegisterUser.Email) != null)
            {
                e.Cancel = true;
                this.Master.SetStatus("warning", Resources.labels.anotherEmail);
            }
        }

        #endregion

    }
}
Mar 28, 2014 at 10:22 AM
Great post, just what I need! Thank you sumnone indeed!