2016-11-29 96 views
3

从Salesforce中使用Google OAuth时,我收到400个错误的请求。以下错误与无效的grant_type有关,但如果您查看'Using Refresh Token'下的文档,您将看到它是正确的。使用Google OAuth2.0时的错误请求

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

错误:

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

我试图访问令牌交换refresh_token,可以成功地做到用它卷曲,用下面的代码。

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); 

回答

5

-d卷曲选项发送中使用其的发送这些参数的所支持的方式之一application/x-www-form-urlencoded内容类型的请求主体中的数据在OAuth2中。

-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相关的参数,而不是在请求体发送它们的。

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

+0

req.setHeader( '内容 - 类型', '应用程序/ x-WWW窗体-urlencoded;字符集= UTF-8'); 我通过删除'charset = UTF-8'来修改上述行,但我仍然收到上面列出的相同错误。 –

+0

你需要改变的是你传递OAuth参数的方式,比如'client_id','grant_type'等。它们不能使用'setHeader',而是在POST请求体中传递。 –

+0

你说得对。 –