SafetyNet 서비스에는 악성 트래픽으로부터 앱을 보호하기 위해 사용할 수 있는 reCAPTCHA API가 포함됩니다.
reCAPTCHA는 고급 위험 분석 엔진을 사용해 스팸 및 다른 악용 작업으로부터 앱을 보호하는 무료 서비스입니다. 이 서비스는 앱과 상호작용 중인 사용자가 사람이 아니라 봇일 수 있다고 의심하면 사람이 해결해야만 앱 실행이 계속될 수 있게 하는 보안문자를 제공합니다.
이 문서에서는 SafetyNet의 reCAPTCHA API를 앱에 통합하는 방법을 설명합니다.
추가 서비스 약관
reCAPTCHA API에 액세스하거나 이를 사용하면 Google API 서비스 약관 및 다음 reCAPTCHA 서비스 약관에 동의하는 것으로 간주됩니다.
SafetyNet API에 액세스하기 전에 모든 관련 약관 및 정책을 자세히 읽고 숙지하시기 바랍니다.
reCAPTCHA 서비스 약관
기기, 애플리케이션 데이터, 무결성 검사 결과와 같은 하드웨어 및 소프트웨어 정보를 수집하고 분석을 위해 이러한 데이터를 Google에 보내는 reCAPTCHA API의 작업을 인정하고 이해하는 것으로 간주됩니다.
Google API 서비스 약관의 3(d)항에 따라, reCAPTCHA API를 사용하면 이러한 데이터를 수집하고 Google과 공유하는 데 필요한 고지 또는 동의를 제공하는 책임이 개발자에게 있다는 것에 동의하는 것으로 간주됩니다.
funonClick(view:View){SafetyNet.getClient(this).verifyWithRecaptcha(YOUR_API_SITE_KEY).addOnSuccessListener(thisasExecutor,OnSuccessListener{response->// Indicates communication with reCAPTCHA service was// successful.valuserResponseToken=response.tokenResultif(response.tokenResult?.isNotEmpty()==true){// Validate the user response token using the// reCAPTCHA siteverify API.}}).addOnFailureListener(thisasExecutor,OnFailureListener{e->if(eisApiException){// An error occurred when communicating with the// reCAPTCHA service. Refer to the status code to// handle the error appropriately.Log.d(TAG,"Error: ${CommonStatusCodes.getStatusCodeString(e.statusCode)}")}else{// A different, unknown type of error occurred.Log.d(TAG,"Error: ${e.message}")}})}
Java
publicvoidonClick(Viewv){SafetyNet.getClient(this).verifyWithRecaptcha(YOUR_API_SITE_KEY).addOnSuccessListener((Executor)this,newOnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>(){@OverridepublicvoidonSuccess(SafetyNetApi.RecaptchaTokenResponseresponse){// Indicates communication with reCAPTCHA service was// successful.StringuserResponseToken=response.getTokenResult();if(!userResponseToken.isEmpty()){// Validate the user response token using the// reCAPTCHA siteverify API.}}}).addOnFailureListener((Executor)this,newOnFailureListener(){@OverridepublicvoidonFailure(@NonNullExceptione){if(einstanceofApiException){// An error occurred when communicating with the// reCAPTCHA service. Refer to the status code to// handle the error appropriately.ApiExceptionapiException=(ApiException)e;intstatusCode=apiException.getStatusCode();Log.d(TAG,"Error: "+CommonStatusCodes.getStatusCodeString(statusCode));}else{// A different, unknown type of error occurred.Log.d(TAG,"Error: "+e.getMessage());}}});}
사용자 응답 토큰 검증하기
reCAPTCHA API가 onSuccess() 메서드를 실행하면 사용자가 보안문자 질문에 성공적으로 답변한 것입니다. 하지만 이 메서드는 사용자가 보안문자를 올바르게 해결했다는 것만 나타냅니다. 여전히 백엔드 서버에서 사용자의 응답 토큰을 검증해야 합니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2023-12-08(UTC)
[null,null,["최종 업데이트: 2023-12-08(UTC)"],[],[],null,["# SafetyNet reCAPTCHA API\n\n| **Warning:** In order to help you safely grow your business, Google builds tools to protect your Android apps and games from abuse. We evolve these solutions as the abuse landscape changes. Delivering on this promise, Google is replacing the SafetyNet reCAPTCHA API with [reCAPTCHA](https://cloud.google.com/recaptcha/docs/instrument-android-apps). reCAPTCHA offers superior protection for mobile applications. We plan to gradually turn down the SafetyNet reCAPTCHA API starting in the third quarter of 2025. Details can be found in the [reCAPTCHA deprecation and shutdown policy](https://cloud.google.com/recaptcha/docs/deprecation-policy-mobile).\n\nThe SafetyNet service includes a reCAPTCHA API that you can use to protect your\napp from malicious traffic.\n\nreCAPTCHA is a free service that uses an advanced risk analysis engine to\nprotect your app from spam and other abusive actions. If the service suspects\nthat the user interacting with your app might be a bot instead of a human, it\nserves a CAPTCHA that a human must solve before your app can continue executing.\n| **Note:** In order to use this API, your app must set `minSdkVersion` to `14` or higher in the `AndroidManifest.xml` file.\n\nThis document explains how to integrate the reCAPTCHA API from SafetyNet into\nyour app.\n\nAdditional terms of service\n---------------------------\n\nBy accessing or using the reCAPTCHA API, you agree to the [Google APIs Terms of\nService](https://developers.google.com/terms/) and to the following reCAPTCHA\nTerms of Service.\nPlease read and understand all applicable terms and policies before accessing\nthe APIs. \n\n### reCAPTCHA Terms of Service\n\nYou acknowledge and understand that the reCAPTCHA API works by collecting hardware and software information, such as device and application data and the results of integrity checks, and sending that data to Google for analysis. Pursuant to Section 3(d) of the Google APIs Terms of Service, you agree that if you use the APIs that it is your responsibility to provide any necessary notices or consents for the collection and sharing of this data with Google.\n\nRegister a reCAPTCHA key pair\n-----------------------------\n\nTo register a key pair for use with the SafetyNet reCAPTCHA API, navigate to the\n[reCAPTCHA Android signup site](https://www.google.com/recaptcha/admin/create),\nthen complete the following sequence of steps:\n\n1. In the form that appears, provide the following information:\n\n - **Label:** A unique label for your key. Typically, you use the name of your company or organization.\n - **reCAPTCHA type:** Select **reCAPTCHA v2** , then **reCAPTCHA Android**.\n - **Packages:** Provide the package name of each app that uses this API key. In order for an app to use the API, the package name that you enter must exactly match the app's package name. Enter each package name on its own line.\n - **Owners:** Add an email address for each individual in your organization who monitors your app's reCAPTCHA assessments.\n2. Select the **Accept the reCAPTCHA Terms of Service** checkbox.\n\n3. **Send alerts to owners:** Select this checkbox if you want to receive\n emails about the reCAPTCHA API, then click\n **Submit**.\n\n4. On the page that appears\n next, your public and private keys appear under **Site key** and **Secret\n key** , respectively. You use the site key when you [send the verify\n request](#send-request), and you use the secret key when you [validate the\n user response token](#validate-response).\n\nAdd the SafetyNet API dependency\n--------------------------------\n\nBefore using the reCAPTCHA API, add the SafetyNet API to your project.\nIf you are using Android Studio, add this dependency to your app-level Gradle\nfile. For more information, see [SafetyNet API setup](https://developer.android.com/training/safetynet#before-you-begin).\n\nUse the reCAPTCHA API\n---------------------\n\nThis section describes how to call the reCAPTCHA API to send a CAPTCHA\nverification request and receive the user response token.\n\n### Send the verify request\n\nTo invoke the SafetyNet reCAPTCHA API, you call the\n[`verifyWithRecaptcha()`](https://developers.google.com/android/reference/com/google/android/gms/safetynet/SafetyNetClient.html#verifyWithRecaptcha(java.lang.String))\nmethod. Usually, this method corresponds to the user's selecting a UI element,\nsuch as a button, in your activity.\n\nWhen using the\n`verifyWithRecaptcha()`\nmethod in your app, you must do the following:\n\n- Pass in your API site key as a parameter.\n- Override the [`onSuccess()`](https://developers.google.com/android/reference/com/google/android/gms/tasks/OnSuccessListener.html#onSuccess(TResult)) and [`onFailure()`](https://developers.google.com/android/reference/com/google/android/gms/tasks/OnFailureListener.html#onFailure(java.lang.Exception)) methods to handle both possible outcomes of the verification request task. In particular, if the API passes an instance of [`ApiException`](https://developers.google.com/android/reference/com/google/android/gms/common/api/ApiException) into `onFailure()`, you need to handle each possible status code that you can retrieve using [`getStatusCode()`](https://developers.google.com/android/reference/com/google/android/gms/common/api/ApiException#getStatusCode()).\n\nThe following code snippet shows how to invoke this method: \n\n### Kotlin\n\n```kotlin\nfun onClick(view: View) {\n SafetyNet.getClient(this).verifyWithRecaptcha(YOUR_API_SITE_KEY)\n .addOnSuccessListener(this as Executor, OnSuccessListener { response -\u003e\n // Indicates communication with reCAPTCHA service was\n // successful.\n val userResponseToken = response.tokenResult\n if (response.tokenResult?.isNotEmpty() == true) {\n // Validate the user response token using the\n // https://developers.google.com/recaptcha/docs/verify.\n }\n })\n .addOnFailureListener(this as Executor, OnFailureListener { e -\u003e\n if (e is ApiException) {\n // An error occurred when communicating with the\n // reCAPTCHA service. https://developers.google.com/android/reference/com/google/android/gms/safetynet/SafetyNetStatusCodes to\n // handle the error appropriately.\n Log.d(TAG, \"Error: ${CommonStatusCodes.getStatusCodeString(e.statusCode)}\")\n } else {\n // A different, unknown type of error occurred.\n Log.d(TAG, \"Error: ${e.message}\")\n }\n })\n}\n```\n\n### Java\n\n```java\npublic void onClick(View v) {\n SafetyNet.getClient(this).verifyWithRecaptcha(YOUR_API_SITE_KEY)\n .addOnSuccessListener((Executor) this,\n new OnSuccessListener\u003cSafetyNetApi.RecaptchaTokenResponse\u003e() {\n @Override\n public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {\n // Indicates communication with reCAPTCHA service was\n // successful.\n String userResponseToken = response.getTokenResult();\n if (!userResponseToken.isEmpty()) {\n // Validate the user response token using the\n // https://developers.google.com/recaptcha/docs/verify.\n }\n }\n })\n .addOnFailureListener((Executor) this, new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n if (e instanceof ApiException) {\n // An error occurred when communicating with the\n // reCAPTCHA service. https://developers.google.com/android/reference/com/google/android/gms/safetynet/SafetyNetStatusCodes to\n // handle the error appropriately.\n ApiException apiException = (ApiException) e;\n int statusCode = apiException.getStatusCode();\n Log.d(TAG, \"Error: \" + CommonStatusCodes\n .getStatusCodeString(statusCode));\n } else {\n // A different, unknown type of error occurred.\n Log.d(TAG, \"Error: \" + e.getMessage());\n }\n }\n });\n}\n```\n\n### Validate the user response token\n\nWhen the reCAPTCHA API executes the\n`onSuccess()`\nmethod, the user has successfully completed the CAPTCHA challenge. However, this\nmethod only indicates that the user has solved the CAPTCHA correctly. You still\nneed to validate the user's response token from your backend server.\n\nTo learn how to validate the user's response token, see [Verifying the user's\nresponse](https://developers.google.com/recaptcha/docs/verify)."]]