【问题标题】:How to use service account .json authentication with powershell?如何在 powershell 中使用服务帐户 .json 身份验证?
【发布时间】:2018-10-08 11:17:11
【问题描述】:
我正在尝试使用 powershell 连接到 google api,甚至认为使用客户端 ID 和客户端密码很简单 - 我使用 this tutorial,我找不到使用为我的项目下载的 service_account 令牌进行身份验证的方法并通过它到我的 api 调用。
【问题讨论】:
-
这是Oauth2 service account 上的文档。我已经尝试过多次让它与 Powershell 一起工作。我放弃了计算签名的某个地方。我永远无法让服务器接受我的代码。祝你好运,如果你能正常工作,我很乐意看到代码。
标签:
powershell
google-api
service-accounts
【解决方案1】:
我设法在 PowerShell 中实现此目的的唯一方法是使用 p12 密钥文件,该文件可以在创建服务帐户时下载。
获得实际令牌也非常令人沮丧。我从我下载的模块中剥离了代码。 https://github.com/scrthq/PSGSuite
function Get-GoogleToken {
[CmdletBinding()]
param(
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$P12KeyPath,
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string[]]
$Scopes,
[parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[String]
$AppEmail,
[parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[String]
$AdminEmail
)
function Invoke-URLEncode ($Object) {
([String]([System.Convert]::ToBase64String($Object))).TrimEnd('=').Replace('+','-').Replace('/','_')
}
$googleCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("$P12KeyPath", "notasecret",[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable )
$rsaPrivate = $googleCert.PrivateKey
$rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider
$rsa.ImportParameters($rsaPrivate.ExportParameters($true))
$rawheader = [Ordered]@{
alg = "RS256"
typ = "JWT"
} | ConvertTo-Json -Compress
$header = Invoke-URLEncode ([System.Text.Encoding]::UTF8.GetBytes($rawheader))
[string]$now = Get-Date (Get-Date).ToUniversalTime() -UFormat "%s"
$createDate = [int]$now.Split(".").Split(",")[0]
$expiryDate = [int]$now.Split(".").Split(",")[0] + 3540
$rawclaims = [Ordered]@{
iss = "$AppEmail"
sub = "$AdminEmail"
scope = "$($Scopes -join " ")"
aud = "https://www.googleapis.com/oauth2/v4/token"
exp = "$expiryDate"
iat = "$createDate"
} | ConvertTo-Json
$claims = Invoke-URLEncode ([System.Text.Encoding]::UTF8.GetBytes($rawclaims))
$toSign = [System.Text.Encoding]::UTF8.GetBytes($header + "." + $claims)
$sig = Invoke-URLEncode ($rsa.SignData($toSign,"SHA256"))
$jwt = $header + "." + $claims + "." + $sig
$fields = [Ordered]@{
grant_type = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
assertion = $jwt
}
$response = Invoke-WebRequest -Uri "https://www.googleapis.com/oauth2/v4/token" -Method Post -Body $fields -ContentType "application/x-www-form-urlencoded"
$messageResponse = $messageResponse | ConvertFrom-Json
return $messageResponse.access_token
}
只需使用正确的参数调用该函数,它应该可以工作!
Get-GoogleToken -P12KeyPath "C:\Users\blabla.p12" -Scopes "https://www.googleapis.com/auth/admin.directory.user" -AppEmail "youreAppEmail@yourapp.com" -AdminEmail "admin@yourapp.com"
希望对你有帮助,
干杯