我目前正在實施服務器端OAuth2流程以授權我的應用程序。Google OAuth2 - 令牌交換訪問代碼 - 不工作
JS應用程序將代表註冊的CMS帳戶向最終用戶(擁有與CMS帳戶合作的渠道)顯示YouTube分析數據。由此,授權階段需要被用戶完全隱藏。我試圖授權一次,然後在需要時使用「永久」授權碼檢索訪問令牌。
我能夠成功授權並檢索訪問碼。當我嘗試交換令牌的訪問代碼時,問題就開始了。
HTTP POST請求實現這一目標需要這個樣子......
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
我使用此代碼來實現這一目標:
var myPOSTRequest = new XMLHttpRequest();
myPOSTRequest.open('POST', 'https://accounts.google.com/o/oauth2/token', true);
myPOSTRequest.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
myPOSTRequest.send('code=' + myAuthCode + '&redirect_uri=http%3A%2F%2Flocalhost%2FCMSAuth3.html&client_id=626544306690-kn5m3vu0dcgb17au6m6pmr4giluf1cle.apps.googleusercontent.com&scope=&client_secret={my_client_secret}&grant_type=authorization_code');
我能順利拿到200 OK響應到此請求,但不返回訪問令牌,並且myPOSTRequest.responseText返回一個空字符串。
我玩過Google的OAuth Playground - 並且可以使用我自己的憑據成功獲取令牌。
我在這裏錯過了什麼嗎?
它看起來像你的代碼,你使用「授權碼」作爲你的授權類型。 – Emily
嗨,艾米麗,我的道歉我粘貼了錯誤的例子 - 用準確的例子編輯使用grant_type = authorization_code – locksem
粘貼實際的http請求和響應。比較這些與Oauth Playground的等價物 – pinoyyid