You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Blazor应用中实现ReCaptcha v3功能?求完整示例

Blazor应用实现ReCaptcha v3完整示例

该方案同时适配Blazor WebAssembly和Blazor Server两种模式。

前置准备

  • 前往Google reCAPTCHA管理控制台申请v3类型的站点密钥(Site Key)和服务端密钥(Secret Key),本地开发可以将localhost加入域名白名单,生产环境替换为实际部署域名。

步骤1:引入前端依赖脚本

找到项目的入口HTML文件:

  • Blazor WebAssembly:wwwroot/index.html
  • Blazor Server:Pages/_Layout.cshtml 或 Pages/_Host.cshtml

在<head>标签中加入reCAPTCHA v3官方脚本:

<script src="https://www.google.com/recaptcha/api.js?render=替换为你申请的SiteKey"></script>

在</body>闭合标签前加入自定义JS方法,用于获取验证token:

window.getReCaptchaV3Token = async (action) => {
  return await grecaptcha.execute('替换为你申请的SiteKey', {action: action});
}

国内环境访问Google服务不稳定的话,可以将域名替换为recaptcha.net使用镜像服务。

步骤2:Blazor组件中调用验证

以提交登录表单的场景为例,示例代码如下:

@inject IJSRuntime JSRuntime
@inject ReCaptchaService CaptchaService

<EditForm Model="@loginModel" OnValidSubmit="@HandleLoginSubmit">
    <div class="form-item">
        <label>用户名</label>
        <InputText @bind-Value="loginModel.UserName" />
    </div>
    <div class="form-item">
        <label>密码</label>
        <InputPassword @bind-Value="loginModel.Password" />
    </div>
    <button type="submit">登录</button>
</EditForm>

@code {
    private LoginFormModel loginModel = new();

    private async Task HandleLoginSubmit()
    {
        // 自定义action参数,用于后台区分验证场景,比如login、register、submit等
        var captchaToken = await JSRuntime.InvokeAsync<string>("getReCaptchaV3Token", "login");
        // 调用服务端验证逻辑
        var isVerifyPass = await CaptchaService.VerifyV3TokenAsync(captchaToken, "login");

        if (isVerifyPass)
        {
            // 验证通过,执行后续登录逻辑
        }
        else
        {
            // 验证失败,提示存在风险操作
        }
    }

    // 表单模型定义
    public class LoginFormModel
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}

步骤3:实现服务端验证逻辑

注意:SecretKey绝对不能暴露给前端,所有验证必须在服务端执行。
首先在Program.cs中注册HTTP客户端和验证服务:

builder.Services.AddHttpClient();
builder.Services.AddScoped<ReCaptchaService>();

实现验证服务ReCaptchaService.cs:

using System.Net.Http.Json;
using System.Text.Json.Serialization;

public class ReCaptchaService
{
    private readonly IHttpClientFactory _httpClientFactory;
    private const string SecretKey = "替换为你申请的SecretKey";
    // 国内环境替换为https://recaptcha.net/recaptcha/api/siteverify
    private const string VerifyApiUrl = "https://www.google.com/recaptcha/api/siteverify";

    public ReCaptchaService(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    public async Task<bool> VerifyV3TokenAsync(string token, string expectedAction)
    {
        using var client = _httpClientFactory.CreateClient();
        var response = await client.PostAsync(VerifyApiUrl, new FormUrlEncodedContent(new Dictionary<string, string>
        {
            {"secret", SecretKey},
            {"response", token}
        }));

        if (!response.IsSuccessStatusCode) return false;

        var verifyResult = await response.Content.ReadFromJsonAsync<ReCaptchaVerifyResponse>();
        // 验证规则:返回成功、action匹配、得分≥0.5(阈值可根据业务调整,范围0-1,值越高验证越严格)
        return verifyResult is { Success: true } 
               && verifyResult.Action == expectedAction 
               && verifyResult.Score >= 0.5m;
    }
}

// 验证接口返回结果实体
public class ReCaptchaVerifyResponse
{
    [JsonPropertyName("success")]
    public bool Success { get; set; }

    [JsonPropertyName("score")]
    public decimal Score { get; set; }

    [JsonPropertyName("action")]
    public string Action { get; set; }

    [JsonPropertyName("error-codes")]
    public List<string> ErrorCodes { get; set; }
}

如果是Blazor WebAssembly项目,不要直接在前端Wasm代码中调用Google验证接口,必须通过你自己的后端服务中转验证,避免SecretKey泄露。

内容的提问来源于stack exchange,提问作者devapi velvet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 08:06:04