Golang调用Google Cloud Identity API获取企业设备列表返回空值求助
问题原因排查及解决方法
1. 核心遗漏配置项
- 缺少服务账号模拟管理员账号的配置:全域权限委派配置完成后,服务账号不能直接调用接口,必须模拟一位拥有谷歌云身份设备管理权限的企业管理员账号,否则会因权限不足返回空列表而非报错。
- 缺少必要的
parent参数:Devices.List()接口必须指定查询的父资源,格式为customers/{客户ID},也可以用customers/my_customer指代当前账号所属的企业,未传该参数时接口默认无返回。 - 权限范围不匹配:你当前使用的
cloud-identity.devices.lookupscope仅支持单设备查询,列表查询需要额外添加https://www.googleapis.com/auth/cloud-identity.devices.readonlyscope。
2. 修正后的Golang代码
package main import ( "context" "fmt" "google.golang.org/api/cloudidentity/v1" "google.golang.org/api/option" ) func main() { // 替换为你企业内拥有设备管理权限的管理员邮箱 adminEmail := "admin@your-domain.com" cloudidentityService, err := cloudidentity.NewService(context.Background(), option.WithCredentialsFile("test.json"), // 新增模拟管理员的配置项 option.ImpersonateCredentials(adminEmail), option.WithScopes( // 替换为设备列表查询所需的scope "https://www.googleapis.com/auth/cloud-identity.devices.readonly", "https://www.googleapis.com/auth/cloud-platform"), ) if err != nil { panic(err) } // 新增必填的parent参数,可替换为你企业实际的customer ID addevices, err := cloudidentityService.Devices.List().Parent("customers/my_customer").Do() if err != nil { panic(err) } if len(addevices.Devices) == 0 { fmt.Println("empty") } else { for _, u := range adddevices.Devices { fmt.Println(u.Name) } return } }
3. Postman调用指导
- 第一步 获取访问令牌:在谷歌云控制台的服务账号页面生成JWT令牌,使用上述提到的权限范围和模拟管理员账号配置,也可以通过OAuth 2.0 Playground生成对应权限的access token。
- 第二步 配置基础请求:请求方法选GET,请求地址填
https://cloudidentity.googleapis.com/v1/devices?parent=customers/my_customer,请求头中添加Authorization: Bearer {你生成的access_token}。 - 第三步 可选过滤配置:如果仅需要查询企业自有设备,可以在请求参数中添加
filter=owner_type:COMPANY,过滤掉员工个人设备。
内容的提问来源于stack exchange,提问作者DEVTEAM
相关产品推荐
相关产品推荐

