Google oauth1迁移到oauth2:无效的授权标头

时间:2015-04-14 12:23:27

标签: oauth migration google-oauth gdata google-oauth2

我坚持将oauth1迁移到oauth2。我不想让我的用户再次授予联系人访问权限,所以我更喜欢自己进行迁移,但我很难弄清楚它为什么不起作用。

我从Google服务器收到此错误:

DEBUG -  << "  "error" : "invalid_request",[\n]"
DEBUG -  << "  "error_description" : "Invalid authorization header."[\n]"

这是我的代码,在使用google api时我做了几乎相同的事情,但是对于迁移它没有用。

GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(getConsumerKey());
oauthParameters.setOAuthConsumerSecret(getConsumerSecret());
oauthParameters.setOAuthToken(token);

ClassPathResource cpr = new ClassPathResource("mykey.pk8");
File file = cpr.getFile();
PrivateKey privKey = getPrivateKey(file);

OAuthRsaSha1Signer signer = new OAuthRsaSha1Signer(privKey);
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer);

String requestUrl = "https://www.googleapis.com/oauth2/v3/token";

String header = oauthHelper.getAuthorizationHeader(requestUrl, "POST", oauthParameters);

String payload = "grant_type=urn:ietf:params:oauth:grant-type:migration:oauth1&client_id="+com.app.framework.utils.OAuthHelper.OAUTH2_CLIENT_ID+"&client_secret="+com.app.framework.utils.OAuthHelper.OAUTH2_CLIENT_SECRET;

HttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost(requestUrl);
httpPost.addHeader("Authorization", header);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setEntity(new ByteArrayEntity(payload.getBytes()));
String response = httpClient.execute(httpPost, new BasicResponseHandler());

2 个答案:

答案 0 :(得分:1)

在与@Miguel交换了一些电子邮件之后,他成功地指出了解决方案。

问题:

GoogleOAuthHelper 扩展的 OAuthHelper 使用 TwoLeggedOAuthHelper 来构建base_string。 TwoLeggedOAuthHelper 没有在base_string中注入3个必需参数: client_id,client_secret grant_type

解决方案:

我必须创建自己的类:将代码从 OAuthHelper 复制/粘贴到 MyOAuthHelper ,然后从 TwoLeggedOAuthHelper 复制/粘贴到 MyTwoLeggedOAuthHelper 。您需要来自 GoogleOAuthHelper 的一些声明来解决编译错误。

MyOAuthHelper 将调用 MyTwoLeggedOAuthHelper 而不是 TwoLeggedOAuthHelper

现在在 MyTwoLeggedOAuthHelper 中,围绕第79行,找到

  

String baseString = OAuthUtil.getSignatureBaseString(baseUrl,   列举HTTPMethod,...

并添加以下内容:

String clientId = "client_id%3DXXX123456789XXX.apps.googleusercontent.com%26";
String clientSecret = "client_secret%3DXXXX_XXXX_XX_XX%26";
String grantType = "grant_type%3Durn%253Aietf%253Aparams%253Aoauth%253Agrant-type%253Amigration%253Aoauth1%26";

baseString = StringUtils.replace(baseString, "token&", "token&" + clientId + clientSecret + grantType);

一些注意事项:

  • client_id和client_secret必须是您的后端用于获取OAUTH1访问令牌的那个。请注意,尤其是如果您在Google控制台中定义了多个“Web应用程序的客户端ID”。

  • 请注意疯狂的grant_type编码两次。

  • 使用的Google课程位于maven:com / google / gdata / core / 1.47.1 / core-1.47.1.jar

感谢@Miguel

答案 1 :(得分:0)

您的请求未通过签名验证。请查看对this related question的回复,详细说明如何为您的请求构建基本字符串并签名。

希望有所帮助!

相关问题