如何在Powershell中使用服务帐户.json身份验证?

时间:2018-10-08 11:17:12

标签: powershell google-api service-accounts

我正在尝试使用Powershell连接到google api,甚至认为使用客户端ID和客户端密码很简单-我使用this tutorial,但是我找不到使用为我的项目下载的service_account令牌进行身份验证的方法并将其传递给我的api调用。

1 个答案:

答案 0 :(得分:0)

我在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"

希望这对您有帮助, 干杯