我看过有关使用 PowerShell 中的个人 OAuth2 令牌使用 Google Drive 操作文件的文章,但没有使用域范围的权限。
据我了解,工作流程是这样的:
- 创建header,base64编码
- 创建声明,base64 编码
- 将 header 和 claim 结合起来,然后用 RSA256 和 Google 提供的私钥进行签名
我在第 3 步遇到问题。请参阅以下代码:
$firstdate = Get-Date -Year 1970 -Month 1 -Day 1 -Hour 0 -Minute 0 -Second 0 -Millisecond 0
$endtime = (New-TimeSpan -Start $firstdate -End (Get-Date).AddMinutes(30).ToUniversalTime()).TotalSeconds
$issuetime = (New-TimeSpan -Start $firstdate -End (Get-Date).ToUniversalTime()).TotalSeconds
$jsonfile = Get-Content 'secret_file.json' | ConvertFrom-Json
$headerhash = [ordered]@{
'alg' = 'RS256'
'typ' = 'JWT'
}
$headerjson = $headerhash | ConvertTo-Json -Compress
$encodedheader = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($headerjson))
$claimhash = [ordered]@{
'iss' = $jsonfile.client_email
'scope' = 'https://www.googleapis.com/auth/drive'
'aud' = 'https://www.googleapis.com/oauth2/v4/token'
'exp' = [math]::Round($endtime,0)
'iat' = [math]::Round($issuetime,0)
}
$claimjson = $claimhash | ConvertTo-Json -Compress
$encodedclaim = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($claimjson))
#$sha = [System.Security.Cryptography.RSACryptoServiceProvider]::Create()
#$sha.Key = [System.Text.Encoding]::UTF8.Getbytes($jsonfile.private_key)
#$sha.FromXmlString($sha.ToXmlString($jsonfile.private_key))
#$signature = $sha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes("$encodedheader.$encodedclaim"))
#$signature = $sha.SignData([System.Text.Encoding]::UTF8.GetBytes("$encodedheader.$encodedclaim"),[System.Security.Cryptography.CryptoConfig]::MapNameToOID('RSASSA-PKCS1-V1_5-SIGN'))
#$encodedsignature = [System.Convert]::ToBase64String($signature)
#$formatter = [System.Security.Cryptography.RSAPKCS1SignatureFormatter]::new($sha)
#$formatter.SetKey($sha)
#$formatter.CreateSignature([System.Text.Encoding]::UTF8.GetBytes("$encodedheader.$encodedclaim"))
$jws = "$encodedheader.$encodedclaim"
$encodedjws = [System.Text.Encoding]::UTF8.GetBytes($jws)
$rsa = [System.Security.Cryptography.RSACryptoServiceProvider]::Create()
# This is the key -- need to convert PEM to proper format
$rsa.FromXmlString($rsa.ToXmlString($jsonfile.private_key))
$sha256OID = [System.Security.Cryptography.CryptoConfig]::MapNameToOID("SHA256")
$signature = $rsa.SignData($encodedjws,$sha256OID)
$encodedsignature = [System.Convert]::ToBase64String($signature)
$jwt = "$encodedheader.$encodedclaim.$encodedsignature"
$requestUri = 'https://www.googleapis.com/oauth2/v4/token'
$method = 'POST'
$body = [ordered]@{
'grant_type' = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
'assertion' = $jwt
}
Invoke-webrequest -Uri $requestUri -Method $method -Body $body -ContentType application/x-www-form-urlencoded
我得到的错误表明 JWT 签名错误。Google 提供的密钥采用 PEM 格式,但我在将其转换为 Powershell 可以理解的内容时遇到了问题。