I would like to retrieve all SAML logs using Google API (I'm using a powershell script to run this task).
I getting the following error while trying to execute the GET request : "Access denied. You are not authorized to read activity records."
These are the steps I followed :
`
$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 = "[email protected]" # Your service account
scope = "https://www.googleapis.com/auth/admin.reports.audit.readonly"
aud = "https://accounts.google.com/o/oauth2/token"
sub = "[email protected]"
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
`
Thank you
The error "Access denied. You are not authorized to read activity records."
appears because the user that is performing the API call doesn't have access to the reports, in this case the service account.
I found this post where it is mentioned that you need to impersonate an Admin in order to access the reports.
Examples from Google in different programming languages show that an admin email is being impersonated:
Based on this sample code you can use the sub
parameter to set the email address of the Admin to impersonate:
$rawclaims = [Ordered]@{
iss = "[email protected]" # Your service account
scope = "https://www.googleapis.com/auth/admin.reports.audit.readonly"
aud = "https://accounts.google.com/o/oauth2/token"
sub = "[email protected]" # The user to impersonate
iat = $createDate
exp = $expiryDate
} | ConvertTo-Json