交换授权代码以进行刷新和访问令牌-错误400

时间:2020-08-18 01:45:51

标签: javascript google-api google-oauth google-signin

当我交换访问令牌和刷新令牌的身份验证代码时,出现400错误

gcp oauth 2凭据设置

  • webapp
  • 重定向https://kii*****jie.chromiumapp.org
  • clientID 423*****5p1.apps.googleusercontent.com
  • 秘密ciA*****JGA

代码

我通过以下方式获取身份验证代码

//js
var url = 'https://accounts.google.com/o/oauth2/v2/auth' + 
              '?client_id=' + clientId + 
              '&response_type=code' + //id_token
              '&access_type=offline' + 
              '&redirect_uri=' + redirectUri + 
              '&scope=' + scopes + 
              '&include_granted_scopes=true'
    chrome.identity.launchWebAuthFlow({'url': url, 'interactive':true},
       function(url) {
           //authcode in url
       }

给定authCode = 4/3AGw0c***70ishchar***7G7LdY

然后我尝试获取访问令牌和刷新令牌的交换身份验证代码

//let url = "https://oauth2.googleapis.com/token" i've also tried this url
let url = "https://www.googleapis.com/oauth2/v4/token"
      const config = {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
      const requestBody = {
        code: authCode,
        redirect_uri: 'https://kii*****jie.chromiumapp.org',
        client_id: '423*****5p1.apps.googleusercontent.com',
        client_secret: 'ciA*****JGA',
        grant_type: "authorization_code"
      }

      const response = await axios.post(url, qs.stringify(requestBody), config)

// qs.stringify(requestBody) = `code=4%2FAGw0c***70ishchar***7G7LdY&
// redirect_uri=https%3A%2F%2Fkii*****jie.chromiumapp.org&
// client_id=423*****opf0pvrr5p1.apps.googleusercontent.com&
// client_secret=ciA*****JGA&
// grant_type=authorization_code`

但是我得到Error: Request failed with status code 400

链接

2 个答案:

答案 0 :(得分:0)

400状态表示您的HTTP请求可能有问题。

应该是没有apps.googleusercontent.com部分的ID吗?

const requestBody = {
        code: authCode,
        redirect_uri: 'https://kii*****jie.chromiumapp.org',
        client_id: '423*****5p1', # CHANGED
        client_secret: 'ciA*****JGA',
        grant_type: "authorization_code"
      }

答案 1 :(得分:0)

好,修复它。

客户端ID不能具有“ .apps.googleusercontent.com”