Search code examples
google-cloud-platformgoogle-cloud-functionsrecaptchacaptcharecaptcha-enterprise

Google.Cloud.RecaptchaEnterprise error on CreateAssessment() - "Request contains an invalid argument"


I'm trying to use the Google.Cloud.RecaptchaEnterprise library to validate captcha requests for the new enterprise key my client has obtained.

string _siteKey = ConfigurationManager.AppSettings["GoogleCaptcha.CheckboxCaptcha.SiteKey"];
string _apiKey = ConfigurationManager.AppSettings["GoogleCaptcha.ApiKey"];
string _projectId = ConfigurationManager.AppSettings["GoogleCaptcha.ProjectId"];
string recaptchaAction = "CreateAccountAssessment";
try {
    var appPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
    string credential_path = appPath + "googlecredentials.json";
    System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path);

    RecaptchaEnterpriseServiceClient client =
    RecaptchaEnterpriseServiceClient.Create();

    CreateAssessmentRequest createAssessmentRequest = new CreateAssessmentRequest()
    {
        Assessment = new Assessment()
        {
            Event = new Event()
            {
                SiteKey = _siteKey,
                Token = formResponse,
                ExpectedAction = "Create_Account"
            },
            Name = recaptchaAction,                         
        },
        Parent = _projectId
    };

    Assessment response = client.CreateAssessment(createAssessmentRequest);

    if (response.TokenProperties.Valid == false)
    {
        Sitecore.Diagnostics.Log.Error("The CreateAssessment() call failed " +
            "because the token was invalid for the following reason: " +
            response.TokenProperties.InvalidReason.ToString(), this);

        return "Invalid captcha.";
    }
    else
    {
        if (response.Event.ExpectedAction == recaptchaAction)
        {
            Sitecore.Diagnostics.Log.Error("The reCAPTCHA score for this token is: " +
                response.RiskAnalysis.Score.ToString(), this);

            return "";
        }
        else
        {
            Sitecore.Diagnostics.Log.Error("The action attribute in your reCAPTCHA " +
                "tag does not match the action you are expecting to score", this);

            return "Invalid captcha.";

        }

    }
}
catch (Exception ex)
{
    Sitecore.Diagnostics.Log.Error("Error validating captcha on " + _url + "; " + ex.Message, this);
    return "Unable to connect to captcha service.";
}

As far as I can tell all my properties are correct, but it throws an error on Assessment response = client.CreateAssessment(createAssessmentRequest);:

Status(StatusCode="InvalidArgument", Detail="Request contains an invalid argument.", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {"created":"@1621287236.280000000","description":"Error received from peer ipv6:[2607:f8b0:4006:81a::200a]:443","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x64\src\core\lib\surface\call.cc","file_line":1062,"grpc_message":"Request contains an invalid argument.","grpc_status":3}")


Solution

  • I strongly suspect the problem (or at least a problem) is the Parent property of the request.

    From the documentation:

    The name of the project in which the assessment will be created, in the format "projects/{project}".

    ... whereas I suspect your project ID is just the ID, rather than the resource name starting with "projects/".

    I would recommend using the generated resource name classes as far as possible, with the corresponding properties. So in this case, you'd have:

    CreateAssessmentRequest createAssessmentRequest = new CreateAssessmentRequest
    {
        Assessment = new Assessment
        {
            Event = new Event
            {
                SiteKey = _siteKey,
                Token = formResponse,
                ExpectedAction = "Create_Account"
            },
            Name = recaptchaAction,                         
        },
        ParentAsProjectName = new ProjectName(_projectId)
    };