使用无符号请求流将Google Oauth1迁移到OAuth2

时间:2014-08-04 22:35:53

标签: java google-oauth

我正在尝试将无符号请求流用作documented(请注意,这不是已签名的请求流),并且只返回HTTP 400:{“error”:“invalid_request”}。这是我正在使用的Java代码(Apache HTTP Client 4.2.x)。

HttpPost httpPost = new HttpPost("https://accounts.google.com/o/oauth2/token");
httpPost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));

List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("grant_type", "urn:ietf:params:oauth:grant-type:migration:oauth1"));
nameValuePairs.add(new BasicNameValuePair("client_id", getClientId()));
nameValuePairs.add(new BasicNameValuePair("client_secret", getClientSecret()));
nameValuePairs.add(new BasicNameValuePair("scope", getScope()));
nameValuePairs.add(new BasicNameValuePair("oauth_consumer_key", getOauthConsumerKey()));
nameValuePairs.add(new BasicNameValuePair("oauth_consumer_secret", getOauthConsumerSecret()));
nameValuePairs.add(new BasicNameValuePair("oauth_token", getOauthToken()));
nameValuePairs.add(new BasicNameValuePair("oauth_token_secret", getOauthTokenSecret()));

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse httpResponse = httpClient.execute(httpPost);

示例请求/响应

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

oauth_consumer_secret=consumerSecret&oauth_consumer_key=consumerKey&oauth_token=token&oauth_token_secret=tokenSecret&client_id=clientId&client_secret=clientSecret&scope=http%3A%2F%2Fspreadsheets.google.com%2Ffeeds%2F+http%3A%2F%2Fdocs.google.com%2Ffeeds+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.file&grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Amigration%3Aoauth1

响应

Status: 400 Bad Request

{
    error: "invalid_request"
}

2 个答案:

答案 0 :(得分:0)

我不熟悉HttpPost.setEntity方法,但似乎是设置帖子正文,而不是OAuth 2.0请求所需的标题。从您链接的文档:

...
Authorization: OAuth realm="example",
           oauth_consumer_key="9djdj82h48djs9d2",
           oauth_token="kkk9d7dh3k39sjv7",
           oauth_signature_method="HMAC-SHA1",
           oauth_timestamp="137131201",
           oauth_nonce="7d8f3e4a",
           oauth_signature="bYT5CMsGcbgUdFHObYMEfcx6bsw%3D"

grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Amigration%3Aoauth1&client_id=8819981768.apps.googleusercontent.com&client_secret=YOUR_CLIENT_SECRET

您可以看到 oauth _ * 进入HTTP请求标头,而 grant_type client_id client_secret 范围应该在HTTP正文中。

答案 1 :(得分:0)

在unsigned-request流程中,OAuth 1.0访问令牌在发出刷新令牌后立即被撤销。 此流仅适用于本机应用程序。来自使用此流程的Web应用程序的请求将被拒绝。