[英]Accessing G Suite Admin SDK using service account
我正在嘗試使用服務帳戶訪問Directory 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訪問的配置步驟?
有這個工作! 域范圍的權限委派和模擬($ 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"
一旦聲明符合授予的權限,我就收到了我的令牌。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.