|
| 1 | +/* |
| 2 | + * Copyright 2022 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package account_defender; |
| 18 | + |
| 19 | +// [START recaptcha_enterprise_account_defender_assessment] |
| 20 | + |
| 21 | +import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient; |
| 22 | +import com.google.protobuf.ByteString; |
| 23 | +import com.google.recaptchaenterprise.v1.AccountDefenderAssessment.AccountDefenderLabel; |
| 24 | +import com.google.recaptchaenterprise.v1.Assessment; |
| 25 | +import com.google.recaptchaenterprise.v1.CreateAssessmentRequest; |
| 26 | +import com.google.recaptchaenterprise.v1.Event; |
| 27 | +import com.google.recaptchaenterprise.v1.ProjectName; |
| 28 | +import com.google.recaptchaenterprise.v1.RiskAnalysis.ClassificationReason; |
| 29 | +import com.google.recaptchaenterprise.v1.TokenProperties; |
| 30 | +import java.io.IOException; |
| 31 | +import java.nio.charset.StandardCharsets; |
| 32 | +import java.security.MessageDigest; |
| 33 | +import java.security.NoSuchAlgorithmException; |
| 34 | +import java.util.List; |
| 35 | +import java.util.UUID; |
| 36 | + |
| 37 | +public class AccountDefenderAssessment { |
| 38 | + |
| 39 | + public static void main(String[] args) throws IOException, NoSuchAlgorithmException { |
| 40 | + // TODO(developer): Replace these variables before running the sample. |
| 41 | + // projectId: Google Cloud Project ID |
| 42 | + String projectId = "project-id"; |
| 43 | + |
| 44 | + // recaptchaSiteKey: Site key obtained by registering a domain/app to use recaptcha |
| 45 | + // services. |
| 46 | + String recaptchaSiteKey = "recaptcha-site-key"; |
| 47 | + |
| 48 | + // token: The token obtained from the client on passing the recaptchaSiteKey. |
| 49 | + // To get the token, integrate the recaptchaSiteKey with frontend. See, |
| 50 | + // https://cloud.google.com/recaptcha-enterprise/docs/instrument-web-pages#frontend_integration_score |
| 51 | + String token = "recaptcha-token"; |
| 52 | + |
| 53 | + // recaptchaAction: The action name corresponding to the token. |
| 54 | + String recaptchaAction = "recaptcha-action"; |
| 55 | + |
| 56 | + // Unique ID of the customer, such as email, customer ID, etc. |
| 57 | + String userIdentifier = "default" + UUID.randomUUID().toString().split("-")[0]; |
| 58 | + |
| 59 | + // Hash the unique customer ID using HMAC SHA-256. |
| 60 | + MessageDigest digest = MessageDigest.getInstance("SHA-256"); |
| 61 | + byte[] hashBytes = digest.digest(userIdentifier.getBytes(StandardCharsets.UTF_8)); |
| 62 | + ByteString hashedAccountId = ByteString.copyFrom(hashBytes); |
| 63 | + |
| 64 | + accountDefenderAssessment(projectId, recaptchaSiteKey, token, recaptchaAction, hashedAccountId); |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * This assessment detects account takeovers. See, |
| 69 | + * https://cloud.google.com/recaptcha-enterprise/docs/account-takeovers The input is the hashed |
| 70 | + * account id. Result tells if the action represents an account takeover. You can optionally |
| 71 | + * trigger a Multi-Factor Authentication based on the result. |
| 72 | + */ |
| 73 | + public static void accountDefenderAssessment( |
| 74 | + String projectId, |
| 75 | + String recaptchaSiteKey, |
| 76 | + String token, |
| 77 | + String recaptchaAction, |
| 78 | + ByteString hashedAccountId) |
| 79 | + throws IOException { |
| 80 | + try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) { |
| 81 | + |
| 82 | + // Set the properties of the event to be tracked. |
| 83 | + Event event = |
| 84 | + Event.newBuilder() |
| 85 | + .setSiteKey(recaptchaSiteKey) |
| 86 | + .setToken(token) |
| 87 | + // Set the hashed account id (of the user). |
| 88 | + // Recommended approach: HMAC SHA256 along with salt (or secret key). |
| 89 | + .setHashedAccountId(hashedAccountId) |
| 90 | + .build(); |
| 91 | + |
| 92 | + // Build the assessment request. |
| 93 | + CreateAssessmentRequest createAssessmentRequest = |
| 94 | + CreateAssessmentRequest.newBuilder() |
| 95 | + .setParent(ProjectName.of(projectId).toString()) |
| 96 | + .setAssessment(Assessment.newBuilder().setEvent(event).build()) |
| 97 | + .build(); |
| 98 | + |
| 99 | + Assessment response = client.createAssessment(createAssessmentRequest); |
| 100 | + |
| 101 | + // Check integrity of the response token. |
| 102 | + if (!checkTokenIntegrity(response.getTokenProperties(), recaptchaAction)) { |
| 103 | + return; |
| 104 | + } |
| 105 | + |
| 106 | + // Get the reason(s) and the reCAPTCHA risk score. |
| 107 | + // For more information on interpreting the assessment, |
| 108 | + // see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment |
| 109 | + for (ClassificationReason reason : response.getRiskAnalysis().getReasonsList()) { |
| 110 | + System.out.println(reason); |
| 111 | + } |
| 112 | + float recaptchaScore = response.getRiskAnalysis().getScore(); |
| 113 | + System.out.println("The reCAPTCHA score is: " + recaptchaScore); |
| 114 | + String assessmentName = response.getName(); |
| 115 | + System.out.println( |
| 116 | + "Assessment name: " + assessmentName.substring(assessmentName.lastIndexOf("/") + 1)); |
| 117 | + |
| 118 | + // Get the Account Defender result. |
| 119 | + com.google.recaptchaenterprise.v1.AccountDefenderAssessment accountDefenderAssessment = |
| 120 | + response.getAccountDefenderAssessment(); |
| 121 | + System.out.println(accountDefenderAssessment); |
| 122 | + |
| 123 | + // Get Account Defender label. |
| 124 | + List<AccountDefenderLabel> defenderResult = |
| 125 | + response.getAccountDefenderAssessment().getLabelsList(); |
| 126 | + // Based on the result, can you choose next steps. |
| 127 | + // If the 'defenderResult' field is empty, it indicates that Account Defender did not have |
| 128 | + // anything to add to the score. |
| 129 | + // Few result labels: ACCOUNT_DEFENDER_LABEL_UNSPECIFIED, PROFILE_MATCH, |
| 130 | + // SUSPICIOUS_LOGIN_ACTIVITY, SUSPICIOUS_ACCOUNT_CREATION, RELATED_ACCOUNTS_NUMBER_HIGH. |
| 131 | + // For more information on interpreting the assessment, see: |
| 132 | + // https://cloud.google.com/recaptcha-enterprise/docs/account-defender#interpret-assessment-details |
| 133 | + System.out.println("Account Defender Assessment Result: " + defenderResult); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + private static boolean checkTokenIntegrity( |
| 138 | + TokenProperties tokenProperties, String recaptchaAction) { |
| 139 | + // Check if the token is valid. |
| 140 | + if (!tokenProperties.getValid()) { |
| 141 | + System.out.println( |
| 142 | + "The Account Defender Assessment call failed because the token was: " |
| 143 | + + tokenProperties.getInvalidReason().name()); |
| 144 | + return false; |
| 145 | + } |
| 146 | + |
| 147 | + // Check if the expected action was executed. |
| 148 | + if (!tokenProperties.getAction().equals(recaptchaAction)) { |
| 149 | + System.out.printf( |
| 150 | + "The action attribute in the reCAPTCHA tag '%s' does not match " |
| 151 | + + "the action '%s' you are expecting to score", |
| 152 | + tokenProperties.getAction(), recaptchaAction); |
| 153 | + return false; |
| 154 | + } |
| 155 | + return true; |
| 156 | + } |
| 157 | +} |
| 158 | +// [END recaptcha_enterprise_account_defender_assessment] |
0 commit comments