62 lines
1.9 KiB
C#
62 lines
1.9 KiB
C#
using System;
|
|
using Google.Api.Gax.ResourceNames;
|
|
using Google.Cloud.RecaptchaEnterprise.V1;
|
|
|
|
namespace Api.Helpers
|
|
{
|
|
public static class ReCaptchaAssessment
|
|
{
|
|
// Checks the supplied token with Recaptcha Enterprise and returns true if valid.
|
|
// Outputs a short reason when false (invalid reason or exception message).
|
|
public static bool CheckToken(string token, out string reason, string projectId = "webserverfarm", string recaptchaKey = "6Lf6df0rAAAAAMXcAx1umneXl1QJo9rTrflpWCvB")
|
|
{
|
|
reason = string.Empty;
|
|
|
|
if (string.IsNullOrWhiteSpace(token))
|
|
{
|
|
reason = "empty-token";
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
var client = RecaptchaEnterpriseServiceClient.Create();
|
|
|
|
var request = new CreateAssessmentRequest
|
|
{
|
|
Parent = $"projects/{projectId}",
|
|
Assessment = new Assessment
|
|
{
|
|
Event = new Event
|
|
{
|
|
SiteKey = recaptchaKey,
|
|
Token = token
|
|
}
|
|
}
|
|
};
|
|
|
|
var response = client.CreateAssessment(request);
|
|
|
|
if (response?.TokenProperties == null)
|
|
{
|
|
reason = "missing-token-properties";
|
|
return false;
|
|
}
|
|
|
|
if (!response.TokenProperties.Valid)
|
|
{
|
|
reason = response.TokenProperties.InvalidReason.ToString();
|
|
return false;
|
|
}
|
|
|
|
reason = "valid";
|
|
return true;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
reason = ex.Message;
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
} |