Skip to main content

Google reCAPTCHA implementation - ASP.NET C#, ASP.NET Web API, Android

Google reCAPTCHA implementation ASP.NET C#

Steps to implement Google reCAPTCHA in your website using technologies such as ASP.NET C#, ASP.NET web API, HTML and javascript. First you need to use your google account to login to
Google reCAPTCHA to register a new site.

Add a label of your choice in the label section and for web implementation select the reCAPTCHA V2 radio button. Next in the domain section you can add several domains, for testing purposes you can add localhost also followed by another domain in the next line.
Accept the terms and conditions and click on the button register.


After you click register, google will generate a site key and a secret key and  instructions how to integrate it on both client and server side.

Create ASP.NET Web API

Next step is to open Microsoft Visual Studio and create a new project by selecting File > New from the menu bar and then select Project. 
Select ASP.NET Web Application(.NET Framework) in the popup windows, give the application a suitable and consistent naming convention then click OK


On the next pop up windows select Web API make sure that both MVC and Web API are checked at the bottom on the windows. Optionally you can change authentication method or add unit tests then click OK








[HttpPost]
[Route("validuser")]
public IHttpActionResult ValidUser()
{
 try
 {
  foreach (string key in HttpContext.Current.Request.Form.AllKeys)
   value = HttpContext.Current.Request.Form["g-recaptcha-response"];

  if (string.IsNullOrEmpty(value))
   return BadRequest("User Token key missing");

  var client = new WebClient();
  url = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, value);
  var response = client.DownloadString(url);
  result = JsonConvert.DeserializeObject<ReCaptchaViewModel>(response);

  if (result.Success == true)
  {
   //Success
  }
  else
  {
   //error
  }

 }
 catch (Exception ex)
 {
  return InternalServerError(ex);
 }
 
 return Ok();
}

Create ASP.NET Web Site

To add a web site in the same solution, right click on solution in the solution explorer from the context menu select Add > New Web Site. After that add a new HTML page in the web site just created.


Add the following HTML elements and make a post request to the API just created.

<!DOCTYPE html>
<html>
<head>
    <script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
    <form action="http://localhost:9062/v1/captcha/validuser" method="POST">
        <div class="g-recaptcha" data-sitekey="YourSiteKeyHere"></div>
        <button type="submit">Login</button>
    </form>
    
</body>
</html>

Testing





Google reCAPTCHA implementation Android

Create a new android application by selecting File > New > New Project 





Open the main activity and on the top you will find the package name, copy it and go to Google reCAPTCHA then select the radio button reCAPTCHA Android and paste the package of the application in the package name section.
Give your reCAPTCHA a suitable name, accept the terms and condition then click on the register button.


Next step is to allow you application to access the internet. You can do so by adding user permission in the AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.kavsoftware.kaveer.googlerecaptcha">

    <!--check internet connection -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_icon"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".Activity.MainActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

To include the reCAPTCHA library in you application, in the Gradle Scripts section select build.gradle(Module: app) add the following line then click on the save icon

dependencies {

    compile 'com.google.android.gms:play-services-safetynet:11.4.2'

}

Now in the layout of the main activity add a button which will trigger  the reCAPTCHA challenge for example a sign up button




In the main activity implement two classes: GoogleApiClient.ConnectionCallBack and GoogleApiClient.OnConnectionFailedListener.

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

}

In the OnCreate() method check for internet connection then make and instantiate a new object for the class GoogleApiCall

@Override
protected void onCreate(Bundle savedInstanceState) {
 this.setTitle(R.string.AppName);

 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
 requestWindowFeature(Window.FEATURE_NO_TITLE);

 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 try {

  if(isNetworkConnected()){
   ConnectToGoogleApi();
  }
  else {
   DisplayToast("No internet Connection");
  }
 }
 catch (Exception ex){
  DisplayToast(ex.getMessage());
 }

}

protected boolean isNetworkConnected() {
 try {
  ConnectivityManager mConnectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
  return (mNetworkInfo == null) ? false : true;

 }catch (NullPointerException e){
  return false;

 }
}

private void ConnectToGoogleApi() {
 mGoogleApiClient = new GoogleApiClient.Builder(this)
   .addApi(SafetyNet.API)
   .addConnectionCallbacks(MainActivity.this)
   .addOnConnectionFailedListener(MainActivity.this)
   .build();

 mGoogleApiClient.connect();
}

Implement the OnClick() method to trigger the reCAPTCHA challenge

Button reCaptchaButton   = findViewById(R.id.BtnSignUp);
reCaptchaButton.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {

  SafetyNet.SafetyNetApi.verifyWithRecaptcha(mGoogleApiClient, SiteKey)
    .setResultCallback(new ResultCallback<SafetyNetApi.RecaptchaTokenResult>() {
     @Override
     public void onResult(SafetyNetApi.RecaptchaTokenResult result) {
      Status status = result.getStatus();

      if ((status != null) && status.isSuccess()) {

       if (!result.getTokenResult().isEmpty()) {
        String endPoint = BuildEndPoint(result.getTokenResult());
        String jsonObject = ValidateUserToken(endPoint);

        DeserializeJsonObject(jsonObject);

        if (response.isSuccess() == true){
         //save user info
         DisplayToast("Data saved");
        }

       }else{
        DisplayToast("Fail to validate user");
       }

      } else {
       DisplayToast("Fail to validate user");
      }
     }
    });


  DisplayToast("Loading Google ReCaptcha...");
 }
});

The last step is to verify the user token generated when the challenge is successfully completed. Use you secret key and user token to make an API call

private String ValidateUserToken(String endPoint) {
 String result = "";

 if(isNetworkConnected()){

  try {
   result = new GetRaceCardFromApi().execute(endPoint).get();
  } catch (InterruptedException e) {
   e.printStackTrace();
  } catch (ExecutionException e) {
   e.printStackTrace();
  }
 }
 else {
  DisplayToast("No internet connection");
 }

 return  result;
}

private class GetRaceCardFromApi extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
 String jsonObject = "";
 try {
  URL url = new URL(params[0]);
  connection = (HttpURLConnection) url.openConnection();
  connection.connect();
  InputStream stream = connection.getInputStream();
  reader = new BufferedReader(new InputStreamReader(stream));
  StringBuffer buffer = new StringBuffer();

  String line ="";

  while ((line = reader.readLine()) != null){
   buffer.append(line);
  }

  jsonObject = buffer.toString();

 } catch (Exception e) {

  Log.e("MainActivity", e.getMessage(), e);

 } finally {
  if(connection != null) {
   connection.disconnect();
  }
  try {
   if(reader != null) {
    reader.close();
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 return jsonObject;
}

package com.kavsoftware.kaveer.googlerecaptcha.ViewModel;

/**
 * Created by kaveer on 11/6/2017.
 */

public class VerifyUserResponseViewModel {
    private boolean success;
    private String challenge_ts;
    private String apk_package_name;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getChallenge_ts() {
        return challenge_ts;
    }

    public void setChallenge_ts(String challenge_ts) {
        this.challenge_ts = challenge_ts;
    }

    public String getApk_package_name() {
        return apk_package_name;
    }

    public void setApk_package_name(String apk_package_name) {
        this.apk_package_name = apk_package_name;
    }
}

private void DeserializeJsonObject(String jsonObject) {
 try {
  VerifyUserResponseViewModel response = new VerifyUserResponseViewModel();
  JSONObject jsonResult = new JSONObject(jsonObject);
  response.setSuccess(jsonResult.getBoolean("success"));
  response.setChallenge_ts(jsonResult.getString("challenge_ts"));
  response.setApk_package_name(jsonResult.getString("apk_package_name"));

 } catch (JSONException e) {
  e.printStackTrace();
 }
}

Testing





Download

Click here to download the source code

Please donate and support at https://www.paypal.me/Rajcoomar

Comments

  1. Shop for the karma herbs. Discover traditional medicine gifts, jamaican black stone premature ejaculation remedies and more. BUY NOW Original Prostaform Herbal Medicine Overcoming Prostate Proven Effective

    ReplyDelete

Post a Comment

Popular posts from this blog

Car Wash System vb.net

This software consists of a database that save the registration number of every vehicle being wash along side with the date, type of wash made and price Screen Shot Source Code To view records in the database: Dim conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\washRcd.accdb;Persist Security Info=False") Dim sql As String sql = " SELECT * FROM tblwash" conn.Open() Dim dt As New DataTable Dim cmd2 As New OleDb.OleDbDataAdapter(sql, conn) cmd2.Fill(dt) DataGridView1.DataSource = dt DataGridView1.Refresh() conn.Close() To insert new record in the database: Private Sub insert() Dim conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\washRcd.accdb;Persist Security Info=False") Dim updateSql As String = String.Format(...

Face recognition using EmguCV 3.0 and typing pattern recognition

Introduction An MSc project with the title Student Examination System, where the objective is to put the students in an examination condition but instead of having an invigilator in an examination center, the system will cater for the proper ongoing of the exam. the system can be used as an online examination system The system is able to: Recognizing the face shape of a particular student Detect if there is more than one person in the examination room  Analyze the typing pattern of a student and detect if any one person is taking part in the exam voice recognition for the student and detect if there is more than one person speaking in the examination room Setup Download Emgu CV from  http://www.emgu.com/wiki/index.php/Main_Page Download Haarcascade from  https://github.com/opencv/opencv/tree/master/data/haarcascades Create an account at  https://www.keytrac.net/ Face recognition The snippet below illustrates how the Emgu CV is loaded whe...

Student Information System - AngularJS , ASP.NET API, C#

Web based application the student information system is a small application that allows user to register and login to view information about a particular student and can perform several actions like Login and register to the application View students  Add new student Delete a particular student Update user information Screen Shot Project architecture routing.js, config.js and app.js allow the application to route from one partial view to another and config.js is used to save all the endpoint needed to access the API.   For separation of concerns, in the solution panel separate partial views, controller and services in different directories and reference it in index.html to enable angular to load all the files required Login process login.html LoginController.js Using $resource from AngularJS to make an API call and response  with a user details model UserViewModel and UserDetailsViewModel Using Unity fo...