.NET MVC部署Google reCAPTCHA Enterprise时默认凭据缺失问题求助
开发环境运行正常,但部署到Windows Server 2022生产服务器后,应用日志报错:Your default credentials were not found,无法正常使用Google reCAPTCHA Enterprise。
已遵循官方文档并尝试以下操作:
- 设置环境变量
GOOGLE_APPLICATION_CREDENTIALS指向.json凭据文件路径,文件存于IIS虚拟目录外,已给应用程序池身份及Everyone赋予读取权限。 - 安装配置gcloud CLI,设置默认项目并执行
gcloud auth application-default login命令,已在Appdata\Roaming\gcloud\application_default_credentials.json生成凭据文件。 - 设置环境变量后已重启IIS及整个服务器。
使用的代码如下:
private const string _key = "<mykey>"; private const string _projectID = "<myprojectid>"; //Just caching my client, as suggested by google internal RecaptchaEnterpriseServiceClient _client { get { if (HttpContext.Current.Session["RecaptchaClient"] != null) { return (RecaptchaEnterpriseServiceClient)HttpContext.Current.Session["RecaptchaClient"]; } else { var client = RecaptchaEnterpriseServiceClient.Create(); HttpContext.Current.Session["RecaptchaClient"] = client; return client; } } } public Assessment Evaluate(string token = "action-token", string recaptchaAction = "action-name") { ProjectName projectName = new ProjectName(_projectID); // Build the assessment request. CreateAssessmentRequest createAssessmentRequest = new CreateAssessmentRequest() { Assessment = new Assessment() { // Set the properties of the event to be tracked. Event = new Event() { SiteKey = _key, Token = token, ExpectedAction = recaptchaAction }, }, ParentAsProjectName = projectName }; Assessment response = _client.CreateAssessment(createAssessmentRequest); return response; }
可尝试的排查及解决思路
直接在代码中显式指定凭据文件:
绕开环境变量依赖,使用RecaptchaEnterpriseServiceClientBuilder直接加载凭据文件,确保路径正确且仅给应用池标识账号授权读取权限(避免给Everyone权限)。修改客户端创建逻辑:var builder = new RecaptchaEnterpriseServiceClientBuilder { CredentialsPath = @"D:\Your\Safe\Path\credentials.json" }; var client = builder.Build();检查应用程序池的环境变量与身份配置:
- IIS应用程序池的
ApplicationPoolIdentity身份无法读取系统级环境变量,可在应用池「高级设置」->「环境变量」中直接添加GOOGLE_APPLICATION_CREDENTIALS及对应路径。 - 临时切换应用池身份为
LocalSystem(仅测试用),验证是否是身份权限导致的问题,之后再换回最小权限身份。 - 用Process Explorer查看
w3wp.exe进程的环境变量,确认GOOGLE_APPLICATION_CREDENTIALS是否存在且路径正确。
- IIS应用程序池的
验证凭据文件有效性与权限:
- 将生产服务器上的凭据文件复制到开发环境替换原有文件,确认文件本身无损坏、权限配置正确。
- 核对凭据文件中的项目ID与代码里的
_projectID是否一致,避免项目不匹配导致的权限问题。
修正gcloud凭据的读取问题:
gcloud auth application-default login生成的凭据存于当前登录用户的AppData目录,而IIS应用池身份(如ApplicationPoolIdentity)的用户目录是C:\Windows\System32\config\systemprofile\AppData,两者不互通。若要使用此方法,需将应用池身份改为执行gcloud命令的用户,或手动将凭据文件复制到应用池身份的AppData对应目录。启用IIS应用池的用户配置文件加载:
在应用池「高级设置」中确保「加载用户配置文件」设置为True,否则应用池无法读取用户目录下的凭据文件,也可能影响环境变量读取。启用Google客户端库日志排查细节:
在Web.config中添加日志配置,查看客户端加载凭据的详细过程,定位具体失败原因:<system.diagnostics> <sources> <source name="Google.Apis" switchValue="Verbose"> <listeners> <add name="file" type="System.Diagnostics.TextWriterTraceListener" initializeData="google_api_logs.txt" /> </listeners> </source> </sources> </system.diagnostics>查看生成的
google_api_logs.txt文件,排查是文件未找到、权限不足还是其他问题。
内容的提问来源于stack exchange,提问作者Jacopo Gucciardi

