【问题标题】:Bad Request when using Google OAuth2.0使用 Google OAuth2.0 时出现错误请求
【发布时间】:2017-04-14 01:34:15
【问题描述】:

我在 Salesforce 中使用 Google OAuth 时收到 400 错误请求。以下错误与无效的 grant_type 有关,但如果您查看“使用刷新令牌”下的文档,您会发现它是正确的。

https://developers.google.com/identity/protocols/OAuth2WebServer

错误:

{
 "error": "unsupported_grant_type",
 "error_description": "Invalid grant_type: "
}

我正在尝试将 refresh_token 交换为访问令牌,并且可以使用 CURL 成功完成此操作,代码如下。

curl \
  -d refresh_token=REFRESH_TOKEN \
  -d client_id=CLIENT_ID \
  -d client_secret=CLIENT_SECRET \
  -d grant_type=refresh_token https://www.googleapis.com/oauth2/v4/token

我在 Salesforce 中使用的代码:

    Http http = new Http();
    HttpRequest req = new HttpRequest();

    req.setHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    req.setHeader('Content-Length', '0');
    req.setHeader('client_id', 'CLIENT_ID');
    req.setHeader('client_secret', 'CLIENT_SECRET');
    req.setHeader('refresh_token', 'REFRESH_TOKEN');
    req.setHeader('grant_type', 'refresh_token'); 

    req.setEndpoint('https://www.googleapis.com/oauth2/v4/token');
    req.setMethod('POST');

    return http.send(req);

【问题讨论】:

    标签: http oauth oauth-2.0 salesforce google-oauth


    【解决方案1】:

    -d curl 选项使用 application/x-www-form-urlencoded 内容类型在请求正文中发送数据,这是在 OAuth2 中发送这些参数的支持方式之一。

    -d 将 POST 请求中的指定数据发送到 HTTP 服务器,就像浏览器在用户填写 HTML 表单并按下提交按钮时所做的一样。这将导致 curl 使用 content-type application/x-www-form-urlencoded 将数据传递给服务器。

    在 Salesforce 代码中,您设置了正确的内容类型,但随后将 OAuth2 相关参数作为附加标头发送,而不是在请求正文中发送。

    您需要更新代码以使用application/x-www-form-urlencoded 编码发送请求正文中的参数。

    【讨论】:

    • req.setHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');我通过删除 'charset=UTF-8' 修改了上面的行,但我仍然收到上面列出的相同错误。
    • 您需要更改的是传递 OAuth 参数的方式,例如 client_idgrant_type 等。它们不能使用 setHeader,而是在 POST 请求正文中传递.
    【解决方案2】:

    我在提琴手中发现了同样的问题。我添加此评论是因为它可能对某人有所帮助。

    https://oauth2.googleapis.com/token
    Content-Type: application/x-www-form-urlencoded
    
    Request Body:
    code=<some code here>&
    client_id=your_client_id&
    client_secret=your_client_secret&
    redirect_uri=https%3A//oauth2.example.com/code&
    grant_type=authorization_code
    

    Goole api 响应:

    {"error": "unsupported_grant_type",  "error_description": "Invalid grant_type: "}
    

    出现问题是因为请求正文的每个参数之间都有换行符。如果您删除所有换行符,将所有值保留在单行请求中将可以正常工作。例如请求正文:

    code=<some code here>&client_id=your_client_id&client_secret=your_client_secret&redirect_uri=https%3A//oauth2.example.com/code&grant_type=authorization_code
    

    【讨论】:

    • 你为我节省了数小时的实验时间!
    猜你喜欢
    • 2014-06-24
    • 2017-02-09
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2021-06-18
    相关资源
    最近更新 更多