使用Google Sign In获取用户性别需配置什么权限范围(Scope)?
解决Google Sign-In无法获取性别字段的问题
Hey there! I’ve run into this exact issue before, so let’s break down the fixes step by step to get that gender data showing up:
1. 明确请求包含性别权限的Scope
Google Sign-In不会默认返回性别信息,你必须主动请求对应的权限Scope。常用的有效选项有两个:
profile:这个Scope涵盖用户的基础个人资料信息(包括性别、生日等,前提是用户在Google账户中填写了这些内容)- 或者更精准的
https://www.googleapis.com/auth/userinfo.profile
以Android为例,你需要在初始化Google Sign-In客户端时添加这个Scope:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .requestProfile() // 关键:添加这一行来申请个人资料权限 .build();
如果使用底层API调用,要确保Scope列表里包含上述权限字符串。
2. 检查Google Cloud Console的OAuth同意屏幕配置
就算代码里加了Scope,如果你的应用在Google Cloud Console的OAuth同意屏幕中没声明需要访问用户个人资料,性别字段还是会返回null:
- 登录Google Cloud Console,找到你的项目
- 进入「API和服务」→「OAuth同意屏幕」
- 在「范围」区域,确认添加了
.../auth/userinfo.profile或profile这个Scope,然后保存更新 - 如果是已发布的生产应用,注意
profile属于非敏感Scope,一般不需要额外审核就能使用
3. 验证测试用户的Google账户信息
有时候问题出在用户端:如果测试用的Google账户本身没填写性别信息,API自然返回null。可以让用户登录Google账户,进入「个人资料」页面确认是否设置了性别。
4. 正确解析返回的用户数据
确保你从正确的字段中提取性别信息。在Android中,通过GoogleSignInAccount获取的方式如下:
GoogleSignInAccount account = ...; // 已获取的登录账户 String gender = account.getGender();
如果用People API获取更详细的资料,需要指定personFields=genders参数:
PeopleService peopleService = new PeopleService.Builder(...) .setApplicationName("你的应用名称") .build(); Person profile = peopleService.people().get("people/me") .setPersonFields("genders") .execute(); if (profile.getGenders() != null && !profile.getGenders().isEmpty()) { String gender = profile.getGenders().get(0).getValue(); }
避坑提醒
- 别搞混Scope:
email权限不包含性别信息,必须单独请求profile相关Scope - 重新授权测试:如果之前已经授权过应用,建议让用户在Google账户的「第三方应用访问权限」中移除你的应用,重新登录授权,确保新的Scope生效
- 用同一测试账户:换测试账户时,记得确认新账户也填写了性别信息
内容的提问来源于stack exchange,提问作者Monu
相关产品推荐
相关产品推荐

