我正在尝试自动执行获取OAuth2
授权码的过程,以用于Google表格。使用PowerShell获取Google表格的OAuth2授权码
我创建了谷歌项目并与http://localhost/oauth2callback
重定向URI我已经成功地通过输入此网址到浏览器手动得到授权码注册吧:
https://accounts.google.com/o/oauth2/v2/auth
?redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback
&response_type=code
&client_id=##CLIENTID##
&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets
&access_type=offline
&include_granted_scopes=true
&state=state_parameter_passthrough_value
...然后通过从Chrome浏览器中显示的结果URL中复制出授权码来提取授权码:
http://localhost/oauth2callback
?state=state_parameter_passthrough_value
&code=##AUTHCODE##
&scope=https://www.googleapis.com/auth/spreadsheets#
我试图复制用PowerShell处理这个过程失败了。我想我错过了一些关于所有这些HTTP重定向工作的基本理解。
我已经尝试了几个变化的主题,包括采取第一个重定向结果并将其与另一个Invoke-WebRequest
调用一起提交,但无论我做什么,我只在第一次调用时才返回一个值,只有当我设置-MaximumRedirection
到0
- 什么我回来不帮助我:
Function getAuthorizationCode($cliids) {
$auturl = "https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=http`%3A`%2F`%2Flocalhost`%2Foauth2callback`&response_type=code`&client_id=$cliids`&scope=https`%3A`%2F`%2Fwww.googleapis.com`%2Fauth`%2Fspreadsheets`&access_type=offline`&include_granted_scopes=true`&state=state_parameter_passthrough_value";
#$autrsp = Invoke-WebRequest -UseBasicParsing -Uri $auturl -UseDefaultCredentials -TimeoutSec 180 -ErrorAction SilentlyContinue;
$autrsp = Invoke-WebRequest -UseBasicParsing -Uri $auturl -UseDefaultCredentials -TimeoutSec 180 -MaximumRedirection 0 -ErrorAction Ignore;
$autrdi = "";
if ($autrsp.StatusCode -ge 300 -and $autrsp.StatusCode -lt 400) {
$autrdi = $autrsp.Headers.Location;
}
return $autrdi;
}
# Force main variables to be non-global
Function myMain($arglis) {
$cliids = "##CLIENTID##";
getAuthorizationCode $cliids;
}
# Force main variables to be non-global
myMain $Args;
这导致:在导致重定向值授权码
https://accounts.google.com/ServiceLogin
?passive=1209600
&continue=https://accounts.google.com/o/oauth2/v2/auth
?redirect_uri%3Dhttp://localhost/oauth2callback
%26response_type%3Dcode
%26client_id%3D##CLIENTID##
%26scope%3Dhttps://www.googleapis.com/auth/spreadsheets
%26access_type%3Doffline
%26include_granted_scopes%3Dtrue
%26state%3Dstate_parameter_passthrough_value
%26from_login%3D1
%26as%3D##LOGINCODE##
&oauth=1
&sarp=1
&scc=1
没有什么,没有我effo rts使用返回的信息也得到了我的授权码。
我已经钻了一堆谷歌和StackOverflow搜索结果,要么我正在寻找错误的东西,或者不知道我在找什么。
我很难过。有人能帮我弄清楚我需要什么方向来引导吗?
谢谢!
随着你的PowerShell你试图打开浏览器供用户进行身份验证,或者你想在PowerShell中完成身份验证?如果你想使用powershell的用户名和密码进行身份验证,你必须使用https://tools.ietf.org/html/rfc6749#section-4.3 –
我试图执行任务直接获取授权代码与Powershell,与没有开放的浏览器。谢谢你的链接。我需要更彻底地阅读它,但乍一看它似乎涵盖了获取身份验证令牌的步骤,而不是授权代码。如果是这样,那不是我正在做的那一步。 –
此外,即使这不是规定的技术,浏览器*可以在没有人为干预的情况下生成结果URL这一事实表明该信息应该可以通过PowerShell脚本进行检索。现在有了一个令人兴奋的机会来了解更多关于幕后浏览器和HTTP以及重定向(哦,我的!)的情况。因此,试图复制这种行为不仅会很有趣,而且会对我有很大的教育意义。所以我真的想知道如何在PowerShell中执行这一步骤。 :-) –