我正在尝试使用服务帐户访问目录API(https://developers.google.com/admin-sdk/directory/v1/reference/users/list)。最简单的任务是列出组织中的用户。这适用于我的用户帐户,使用OAuth 2.0 Playgorund进行测试。但我需要使用服务帐户。我正在关注两条腿OAuth(https://developers.google.com/identity/protocols/OAuth2ServiceAccount)的文档并在Powershell中实现REST客户端
Powershell代码:
# Forming the JWT claim set
$cert = Get-PfxCertificate -FilePath "c:\ps\GAdmin\apiaccess-123456.p12" -Password (ConvertTo-SecureString "notasecret" -AsPlainText -Force)
$now = (Get-Date).ToUniversalTime()
$createDate = [Math]::Floor([decimal](Get-Date($now) -UFormat "%s"))
$expiryDate = [Math]::Floor([decimal](Get-Date($now.AddHours(1)) -UFormat "%s"))
$rawclaims = [Ordered]@{
iss = "p12service@apiaccess-123456.iam.gserviceaccount.com"
scope = "https://www.googleapis.com/auth/admin.directory.user"
aud = "https://www.googleapis.com/oauth2/v4/token"
iat = $createDate
exp = $expiryDate
} | ConvertTo-Json
# Encoding the JWT claim set
$jwt = New-Jwt -PayloadJson $rawclaims -Cert $cert -Verbose
# Making the access token request
$apiendpoint = "https://www.googleapis.com/oauth2/v4/token"
$splat = @{
Method = "POST"
Uri = $apiendpoint
ContentType = "application/x-www-form-urlencoded"
Body = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$jwt"
}
$res = Invoke-WebRequest @splat -Verbose
$accesstoken = ($res.content | ConvertFrom-Json).access_token
# Calling Google APIs - list of users
$usersapiendpoint = "https://www.googleapis.com/admin/directory/v1/users?list&customer=my_customer&domain=mydomain.com.au"
$splat = @{
Method = "GET"
Uri = $usersapiendpoint
Headers = @{authorization = "Bearer $accesstoken"}
}
$userlistres = Invoke-WebRequest @splat -Verbose
这导致错误:
code 403, "Not Authorized to access this resource/api"
调用其他API有效。要启用对Directory API的编程访问,我需要执行哪些操作?我是否缺少服务帐户/ SDK访问的配置步骤?
答案 0 :(得分:0)
搞定了!域范围的权限委派和模拟(在$ rawclaims中的sub = "user@example.com"
项)是必要且正确的。
问题在于,通过域范围委派授予服务帐户的特权与我的主张中所请求的特权(我有几个)不匹配:
scope = "https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/iam https://www.googleapis.com/auth/cloud-platform"
一旦声明匹配授予的特权,我就会收到我的令牌。