使用Google API和Powershell检索SAML日志

7cwmlq89  于 2023-05-07  发布在  Shell
关注(0)|答案(1)|浏览(99)

我想使用API检索所有SAML日志(我使用powershell脚本来运行此任务)。我在尝试执行GET请求时得到以下错误:"Access denied. You are not authorized to read activity records."
以下是我遵循的步骤:
1.创建Google Cloud Platform项目并启用“Admin SDK API”
1.创建服务帐户并下载JSON格式的密钥
1.已在Google管理控制台上使用其客户端ID注册服务帐户,范围为“https://www.googleapis.com/auth/admin.reports.audit.readonly”(域范围委派配置)
1.使用提供的凭证(JSON文件)创建证书和JWT令牌(请参阅下面的代码)
1.已获得访问令牌并执行GET请求

$cert = $cert = Get-PfxCertificate -FilePath "./cer.pfx" -Password (ConvertTo-SecureString "..." -AsPlainText -Force) # The service account credentials

$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 = "test@test.iam.gserviceaccount.com" # Your service account
    scope = "https://www.googleapis.com/auth/admin.reports.audit.readonly"
    aud = "https://accounts.google.com/o/oauth2/token"
    sub = "test@test.iam.gserviceaccount.com"
    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://oauth2.googleapis.com/token"
$splat = @{
    Method      = "POST"
    Uri         = $apiendpoint
    ContentType = "application/x-www-form-urlencoded"
    Body        = "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=$jwt"
}

# Get access token to authenticate with SPN
try {
    $res = Invoke-RestMethod @splat -Verbose
}
catch {
    [Console]::Error.WriteLine("Error during GCP authentication : $_")
}

# Get SAML logs
$headers = @{
    "Authorization" = "Bearer $($res.access_token)"
}
$uri = "https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/saml"
$response = Invoke-RestMethod -Uri $uri -Method Get -Headers $headers
$response


谢谢你

gcuhipw9

gcuhipw91#

出现错误"Access denied. You are not authorized to read activity records."是因为执行API调用的用户无权访问报告,在本例中是服务帐户。

  • 我找到了this post,其中提到您需要模拟管理员才能访问报告。
  • 来自Google的不同编程语言的示例显示,管理员电子邮件正在被模拟:
  • java
  • 基于this sample code,您可以使用sub参数设置要模拟的管理员的电子邮件地址:
$rawclaims = [Ordered]@{
    iss = "test@test.iam.gserviceaccount.com" # Your service account
    scope = "https://www.googleapis.com/auth/admin.reports.audit.readonly"
    aud = "https://accounts.google.com/o/oauth2/token"
    sub = "admin@yourgoogleworkspacedomain.com" # The user to impersonate
    iat = $createDate
    exp = $expiryDate
} | ConvertTo-Json

相关问题