使用Google OAuth2.0时请求错误 [英] Bad Request when using Google OAuth2.0

查看:77
本文介绍了使用Google OAuth2.0时请求错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Salesforce中使用Google OAuth时,我收到一个400错误的请求.以下是关于无效的grant_type的错误,但是如果您查看使用刷新令牌"下的文档,则会发现它是正确的.

I am receiving a 400 bad request when using Google OAuth from within Salesforce. The following error is in regards to invalid grant_type, but if you look at the documentation under 'Using Refresh Token' you will see that it is correct.

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

错误:

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

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

I am attempting to exchange a refresh_token for an access token and can successfully do it using CURL, with the following code.

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中使用的代码:

The code that I am using inside 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);

推荐答案

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

The -d curl option sends the data in the request body using the application/x-www-form-urlencoded content type which is one of the supported ways of sending those parameters in OAuth2.

-d 将POST请求中的指定数据发送到HTTP服务器,就像用户填写HTML表单时浏览器执行的操作一样.按下提交按钮.这将导致curl使用内容类型application/x-www-form-urlencoded将数据传递到服务器.

-d Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded.

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

In the Salesforce code you're setting the correct content type, but then are sending the OAuth2 related parameters as additional headers instead of sending them in the request body.

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

You need to update the code to send the parameters in the request body using the application/x-www-form-urlencoded encoding.

这篇关于使用Google OAuth2.0时请求错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆