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

C# Windows Form : PetCare

Fake Call Android Application

Car Wash System vb.net