我想从Powershell调用Google API。谷歌文档说:
curl "https://accounts.google.com/o/oauth2/token"
-d "client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&code=$CODE&grant_type=authorization_code&redirect_uri=urn:ietf:wg:oauth:2.0:oob"
从命令行执行时有效。
我尝试将其转换为powershell,如:
$token = Invoke-WebRequest -Uri "https://accounts.google.com/o/oauth2/token" -Method POST -Body "client_id=x&client_secret=y&code=z&grant_type=authorization_code&redirect_uri=urn:ietf:wg:oauth:2.0:oob"
并且喜欢:
$tokenParams = @{
client_id='x';
client_secret='y';
code='z';
grant_type='authorization_code';
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
}
$token = Invoke-WebRequest -Uri "https://accounts.google.com/o/oauth2/token" -Method POST -Body $tokenParams
两者都返回:
Invoke-WebRequest : The remote server returned an error: (400) Bad Request.
如何正确地将curl转换为Invoke-WebRequest或其他PS cmdlet?
答案 0 :(得分:0)
理论上你使用 Invoke-WebRequest ,因为POST请求的正文应该有 application / x-www-form-urlencoded 内容类型,默认情况下在PS中设置。
我执行了相同的代码,我收到了401请求,因为我的auth参数不匹配。我也在Fiddler中检查了它并且消息构造正确
Mine Fiddler捕获的Invoke-WebRequest POST消息如下:
POST https://accounts.google.com/o/oauth2/token HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT; Windows NT 6.4; hu-HU) WindowsPowerShell/5.0.9879.0
Content-Type: application/x-www-form-urlencoded
Host: accounts.google.com
Content-Length: 113
Expect: 100-continue
Connection: Keep-Alive
grant_type=authorization_code&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&code=z&client_id=x&client_secret=y
根据Google的oauth示例消息(https://developers.google.com/accounts/docs/OAuth2ForDevices),这是正确的,所以我也会检查你在Fiddler的电话。