如何用Google Integrity API保护Xamarin.Forms Android应用及使用对应NuGet?
在Xamarin.Forms Android应用中使用Google Integrity API的步骤
1. 前置准备
- 确保你的应用已在Google Play Console完成注册,且Android项目包名与Play Console中一致
- 在Play Console的「API和服务」页面启用Google Play Integrity API
- 获取你的Google Cloud项目编号(后续请求时需要用到)
2. 安装NuGet包
在Xamarin.Forms的Android项目中,通过NuGet包管理器搜索并安装Xamarin.Google.Android.Play.Integrity包。
3. 实现平台专属调用逻辑
Integrity API是Android平台专属功能,需通过依赖服务实现跨平台调用:
3.1 定义共享接口(PCL/共享项目)
public interface IIntegrityService { Task<string> FetchIntegrityToken(string nonce); }
3.2 编写Android平台实现
在Android项目中创建实现类:
[assembly: Dependency(typeof(IntegrityService))] namespace YourApp.Droid { public class IntegrityService : IIntegrityService { public async Task<string> FetchIntegrityToken(string nonce) { try { // 初始化IntegrityManager var integrityManager = IntegrityManagerFactory.Create(Android.App.Application.Context); // 构建请求参数 var tokenRequest = IntegrityTokenRequest.InvokeBuilder() .SetNonce(nonce) // 随机字符串,建议由后端生成传递,防重放攻击 .SetCloudProjectNumber(你的云项目编号) // 替换为实际项目编号 .Build(); // 请求完整性令牌 var response = await integrityManager.RequestIntegrityTokenAsync(tokenRequest); return response.Token; } catch (Exception ex) { Console.WriteLine($"Integrity API调用失败: {ex.Message}"); return null; } } } }
4. 在共享代码中调用并验证
在Xamarin.Forms的共享代码里调用依赖服务,获取令牌后发送到后端验证:
var integrityService = DependencyService.Get<IIntegrityService>(); // 非字符串建议从后端获取,保证唯一性 var nonce = "随机生成的唯一字符串"; var integrityToken = await integrityService.FetchIntegrityToken(nonce); if (!string.IsNullOrEmpty(integrityToken)) { // 将令牌发送到后端服务器,由后端完成验证逻辑 }
5. 后端验证(核心环节)
令牌必须在后端验证,不能在客户端处理:
- 使用Google官方提供的验证工具(REST API或服务端SDK)解析令牌
- 检查令牌中的
appIntegrity、deviceIntegrity字段,确认应用为正版、设备合规 - 根据验证结果决定是否允许用户进行敏感操作
关键注意事项
- 非字符串(nonce)必须唯一且随机,建议由后端生成后传递给客户端
- 确保应用已开启Google App Signing签名,否则Integrity API无法正常返回有效结果
- 处理API调用异常:如网络错误、API配额超限、设备不支持等情况
内容的提问来源于stack exchange,提问作者Anand
相关产品推荐
相关产品推荐

