web-dev-qa-db-ja.com

asp.netアプリケーションにInvisibleGoogle reCaptchaを実装しますか?

これは私のASP.NETフォームです。サーバー側の検証を使用して、非表示のrecaptchaを追加したいと思います。誰か助けてもらえますか?

クライアント側の検証はできますが、秘密鍵を使用しません。私のもう1つの質問は、目に見えないreCAPTCHAの秘密鍵が必要ですか?

Google recaptchaに使用したサーバーサイドコードを参照してください。ただし、Invisiblerecaptchaでは機能しません。このエラーが発生します:-reCAPTCHAエラー:missing-input-response:Not Valid Recaptcha

<div id="ContactFormDiv" runat="server">
    <div class="form-row form-required">
        <asp:Label ID="YourNameLabel" runat="server" AssociatedControlID="YourNameTextBox"> Your Name:</asp:Label>
        <asp:TextBox ID="YourNameTextBox" runat="server" CssClass="form300" MaxLength="150"></asp:TextBox>
    </div>
    <div class="form-row form-required">
            <div id='recaptcha' class="g-recaptcha"
                data-sitekey="site key"
                data-callback="onSubmit"
                data-size="invisible">
            </div>
    </div>
    <div class="form-row-buttons">
        <asp:Button ID="SendMessageButton" ClientIDMode="Static" runat="server" Text="Send Message" CssClass="buttonPositive"
            CausesValidation="True" OnClick="SendMessageButton_Click" />
    </div>
</div>

Javascriptコード

 <script type="text/javascript" src="https://www.google.com/recaptcha/api.js" async defer></script>

サーバーサイドコード

  public class MyObject
{
    public string success { get; set; }
}

public static string ReCaptcha_Key = "------------------Site Key-----------------";
public static string ReCaptcha_Secret = "--------------Secret Key ---------------";

 public bool ValidateReCaptcha()
{
    bool Valid = false;
    //start building recaptch api call
    var sb = new StringBuilder();

    //Getting Response String Append to Post Method
    string Response = Request["g-recaptcha-response"];

    string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + ReCaptcha_Secret + "&response=" + Response;
    sb.Append(url);

    //make the api call and determine validity
    using (var client = new WebClient())
    {
        var uri = sb.ToString();
        var json = client.DownloadString(uri);
        var serializer = new DataContractJsonSerializer(typeof(RecaptchaApiResponse));
        var ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        var result = serializer.ReadObject(ms) as RecaptchaApiResponse;

        //--- Check if we are able to call api or not.
        if (result == null)
        {
            lblmsg.Text = "Captcha was unable to make the api call";
        }
        else // If Yes
        {
            //api call contains errors
            if (result.ErrorCodes != null)
            {
                if (result.ErrorCodes.Count > 0)
                {
                    foreach (var error in result.ErrorCodes)
                    {
                        lblmsg.Text = "reCAPTCHA Error: " + error;
                    }
                }
            }
            else //api does not contain errors
            {
                if (!result.Success) //captcha was unsuccessful for some reason
                {
                    lblmsg.Text = "Captcha did not pass, please try again.";
                }
                else //---- If successfully verified. Do your rest of logic.
                {
                    lblmsg.Text = "Captcha cleared ";
                    Valid = true;
                }
            }
        }
    }
    return Valid;
}

public bool temp = true;
protected void SendMessageButton_Click(object sender, EventArgs e)
{
    temp = ValidateReCaptcha();
    if (temp == false)
    {
        lblmsg.Text = "Not Valid Recaptcha";
        lblmsg.ForeColor = System.Drawing.Color.Red;
    }
    else
    {
        lblmsg.Text = "Successful";
        lblmsg.ForeColor = System.Drawing.Color.Green;
    }

    Page.Validate();

    if (this.Page.IsValid == true && temp == true)
    { //Page and invisible recaptcha is valid  }
 }

このエラーが発生します:-reCAPTCHAエラー:missing-input-response:Not Valid Recaptcha

5
Satpal Singh

これは私が作業サンプルを実装した方法です:

-クライアント側( Googleドキュメント を参照)

<head>
        <!-- Google Invisible Captcha -->
        <script src='https://www.google.com/recaptcha/api.js'/>
        <script>
        function onSubmit(token) {
            document.getElementById("htmlForm").submit();
        }
        </script>
</head>
<body>
        <form id="htmlForm" action="Default.aspx" method="post">
                <input name="txtName"  />
                <input name="txtEmailAddress"  />
                <button class="g-recaptcha btn btn-default"
                    data-sitekey="-------------------Site key--------------"
                    data-callback="onSubmit">
                    Submit Request
                </button>
        </form>
</body>

-サーバー側(秘密鍵を保持)

    public static bool IsValidCaptcha()
    {

        var secret = "--------------Secret Key ---------------";
        var req =
            (HttpWebRequest)
                WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" + secret + "&response=" + HttpContext.Current.Request.Form["g-recaptcha-response"]);

        using (var wResponse = req.GetResponse())
        {

            using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
            {
                string responseFromServer = readStream.ReadToEnd();
                if (!responseFromServer.Contains("\"success\": false"))
                    return true;
            }
        }

        return false;

    }
6
Barsham

私も同様の問題を抱えており、まともな例を見つけるのは難しいようです。ただし、data-callback = "onSubmit"を設定していることはわかりましたが、そのメソッドをどこで定義したかはわかりませんでした。そこにいますか?それはあなたが欠けているものでしょうか?

0
Xequtor