我正在嘗試自動執行獲取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中執行這一步驟。 :-) –