How to Use ReCaptcha V3 in ASP.NET Core MVC

In this post, we are going to use Google reCaptcha V3 in ASP.NET Core MVC project.

First thing first how a Google reCaptcha V3 works. In reCaptcha V3 user doesn’t interact with any reCaptcha verification directly or solve any puzzle. In V3 we configure a Google API on the front-end that returns us a token and on the server-side. We call another google API that confirms the token. After confirming the token, Google Server-side API verifies the user’s response/token responses to us with a success score that can be 0 to 0.1. If the score is near 0.1 it means the user is human and if the score is ZERO or near to ZERO. it means the request is from the bot.

First of all, create a project.

open Visual Studio and click on create a new project

reCaptcha v3 in ASP.NET Core

Now select a project and click on Next.

reCaptcha v3 in ASP.NET Core

Now name your project and click Next.

reCaptcha v3 in ASP.NET Core

Now we will select Individual Account in “Authentication type” and check “configure for HTTPS” and click on create.

reCaptcha v3 in ASP.NET Core

Now your project will look like this.

reCaptcha v3 in ASP.NET Core

Now run your project and register.

reCaptcha v3 in ASP.NET Core

Register yourself.

reCaptcha v3 in ASP.NET Core

when we click on register we will face an error.

reCaptcha v3 in ASP.NET Core

Now click on Apply migration.

After Applying migration click on confirm email or else you will not be able to login.

reCaptcha v3 in ASP.NET Core

Now you can login. These were the steps to set up our project now we will move on to the main topic that how can we use Google ReCaptcha V3 in this ASP.NET Core MVC Project.

First of all, we have to configure our project with google reCaptcha V3. To configure reCaptcha go to this link.

After going to the above-mentioned link we will see the screen something like this.

reCaptcha v3 in ASP.NET Core

Click on this plus(+) sign and we will get a form to register our site.

reCaptcha v3 in ASP.NET Core

Now we will add info, our domain is localhost now. submit the form.

After registering our ReCaptcha, we will have our “SITEKEY” and “SECRETKEY”.

reCaptcha v3 in ASP.NET Core

Now let’s move back to our ASP.NET Core project and scaffold the Identity login and register page so we can add reCaptcha to them.

Right Click on Area -> Add -> New Scaffold Item

reCaptcha v3 in ASP.NET Core

Then we will have a screen like

reCaptcha v3 in ASP.NET Core

Select Identity and click on Add. After Adding select login and register as we did and select DB context. If you want to apply on some other page it’s your choice.

reCaptcha v3 in ASP.NET Core

Now we have a login.cshtml and register.cshtm page.

reCaptcha v3 in ASP.NET Core

Now we will just past this code on our Login page.

<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
<script>
        grecaptcha.ready(function () {
            grecaptcha.execute('reCAPTCHA_site_key', { action: 'submit' }).then(function (token) {
                // Add your logic to submit to your backend server here.
                console.log(token);
            });
        });

</script>

Add your replace “reCAPTCHA_site_key” with your Google ReCaptcha Site key. We will replace it and run our project. Now we can see reCaptcha sign our login page.

reCaptcha v3 in ASP.NET Core

After calling the reCaptcha API it’s returning a token that we can see in our console.log(token). Now we have to implement our backend configuration to confirm this token on every request.

Now we will add a new class into our project and name it “reCaptchaService.cs” and implement our server-side logic to verify user response. In this “reCaptchaService.cs” class we have created one method and two model classes to send data and get a response from google API. To send Data we have created “reCaptchaData” and to receive a response we have “reCaptchaRespo” class. Let’s move to the main logic we have created a public method “tokenVerify” to call reCaptcha API and deserialize its response into our “reCaptchaRespo” class.

Let’s see the code.

public class reCaptchaService
    {
        public virtual async Task<reCaptchaRespo> tokenVerify(string token)
        {
            reCaptchaData data = new reCaptchaData
            {
                response = token,
                secret = "reCAPTCHA_secret_key"
            };

            HttpClient client = new HttpClient();
            var response = await client.GetStringAsync($"https://www.google.com/recaptcha/api/siteverify?secret={data.secret}&response={data.response}");
            var reCaptcharesponse = JsonConvert.DeserializeObject<reCaptchaRespo>(response);
            return reCaptcharesponse;
        }
    }
    public class reCaptchaData
    {
        public string response { get; set; }
        public string secret { get; set; }
    }
    public class reCaptchaRespo
    {
        public bool success { get; set; }
        public DateTime challenge_ts { get; set; }
        public string hostname { get; set; }
        public long score { get; set; }
    }

We have created our service to verify user’s responses from Google reCaptcha API.

Now configure our service “reCaptchaService.cs” in “Startup.cs” file.

services.AddTransient<reCaptchaService>();

Now we will call our method when the user tries to login. we have created an extra field for tokens in our login form.

<input id="input-token" asp-for="Input.token" />

and created token property in the input model.

[Required]
 public string token { get; set; }

Now we have to assign google generated token to this input field that we have added into our login form by simple Jquery.

$("#input-token").val(token);

after pasting it in our login script our google reCaptcha front-end configuration will look like this.

grecaptcha.ready(function () {
      grecaptcha.execute('reCAPTCHA_site_key', { action: 'submit' }).then(function (token) {
          console.log(token);
              $("#input-token").val(token);
                // Add your logic to submit to your backend server here.
       });
   });

Our Login form will look like this.

reCaptcha v3 in ASP.NET Core

To open “Login method” we will open “Login.cshtml.cs”.

reCaptcha v3 in ASP.NET Core

Now we will inject the “reCaptchaService.cs” class object in our “Login.cshtml.cs” to call the method from this class.

private readonly reCaptchaService _reCaptchaService;
public LoginModel(reCaptchaService reCaptchaService)
{
  _reCaptchaService = reCaptchaService;
}

Now we will move to “OnPostAsync” method in the same “Login.cshtml.cs” class and call our “tokenVerify” method from the “OnPostAsync”.

//google reCaptcha confirmation
var reCaptcharesult = _reCaptchaService.tokenVerify(Input.token);
if(!reCaptcharesult.Result.success && reCaptcharesult.Result.score <= 0.5)
{
  ModelState.AddModelError(string.Empty, "You are not a human.");
  return Page();

}

After adding this to your “OnPostAsync” method our method will look something like this.

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
  returnUrl ??= Url.Content("~/");

  //google reCaptcha confirmation
  var reCaptcharesult = _reCaptchaService.tokenVerify(Input.token);
  if(!reCaptcharesult.Result.success && reCaptcharesult.Result.score <= 0.5)
  {
    ModelState.AddModelError(string.Empty, "You are not a human.");
    return Page();

  }

  ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

  if (ModelState.IsValid)
  {
    // This doesn't count login failures towards account lockout
    // To enable password failures to trigger account lockout, set lockoutOnFailure: true
    var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
    if (result.Succeeded)
    {
      _logger.LogInformation("User logged in.");
      return LocalRedirect(returnUrl);
    }
    if (result.RequiresTwoFactor)
    {
      return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
    }
    if (result.IsLockedOut)
    {
      _logger.LogWarning("User account locked out.");
      return RedirectToPage("./Lockout");
    }
    else
    {
      ModelState.AddModelError(string.Empty, "Invalid login attempt.");
      return Page();
    }
  }

  // If we got this far, something failed, redisplay form
  return Page();
}

When the user clicks “Login” this method will get called and in his method, we have called our “reCaptchaService.cs” method to verify that the request is from a human or not. In this method, we will pass the token to our “tokenVerify(token)” method it will confirm us the user is human or a bot.

After this, we have added the condition if the result is not true and the response score from Google API is less than 0.5 considering the request is from the bot and does not allow the user to login.

I have sorted and enlisted some most important ASP.NET MVC Interview Questions according to current market. Try to read this before any interview.

Conclusion:

Try this tutorial and if you do not understand anything or face any issue while applying this method. Do not hesitate to comment below. My Code Bit team will try to respond ASAP.

Happy coding!

Comments

V

if a user fails 0.5 score test – how they can fix that? can you promote invisible v3 captcha to a full UI challenge so the user can prove they are human after all?

[email protected]

Thanks for your concern and let us know about this. But normally it doesn’t happen. I will try to make a tutorial on this ASAP.

Leave a Reply

Your email address will not be published.