gpt4 book ai didi

java - 从 OAuth2.1 迁移到 OAuth2.0

转载 作者:行者123 更新时间:2023-11-30 03:54:28 26 4
gpt4 key购买 nike

我有一个 GWT Web 应用程序。我有一张大 table ,里面有谷歌 token 和 token secret 。我想迁移到 OAuth2.0 而不重新验证用户身份。我在Java测试中尝试了以下内容

  String url = "https://accounts.google.com/o/oauth2/token";

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

String generatedString = Utils.generateRandomString(10);
String key = new Date().getTime() + "";

// add header
post.setHeader("Host", "accounts.google.com");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setHeader("Authorization", "OAuth " +
"oauth_consumer_key=\"" + CONSUMER_KEY + "\"," +
"oauth_token=\"" + token + "\"," +
"oauth_signature_method=\"HMAC-SHA1\"" +
"timestamp=\"" + key + "\"," +
"oauth_nonce=\"" + generatedString + "\"," +
"oauth_signature=\"" + calculateRFC2104HMAC(key, generatedString) + "\"," +
"oauth_signature_method=\"HMAC-SHA1\"");

List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();

urlParameters.add(new BasicNameValuePair("grant_type", "urn:ietf:params:oauth:grant-type:migration:oauth1"));
urlParameters.add(new BasicNameValuePair("client_id", CONSUMER_KEY));
urlParameters.add(new BasicNameValuePair("client_secret", CONSUMER_SECRET));
urlParameters.add(new BasicNameValuePair("oauth_consumer_key", CONSUMER_KEY));
urlParameters.add(new BasicNameValuePair("oauth_consumer_secret", CONSUMER_SECRET));
urlParameters.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1"));
urlParameters.add(new BasicNameValuePair("oauth_timestamp", "" + new Date().getTime()));
urlParameters.add(new BasicNameValuePair("oauth_token", token));
urlParameters.add(new BasicNameValuePair("oauth_token_secret", token));

post.setEntity(new UrlEncodedFormEntity(urlParameters));

HttpResponse response = client.execute(post);

System.out.println("Sending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

StringBuffer result = new StringBuffer();
String line;

while ((line = rd.readLine()) != null) {
result.append(line);
}

System.out.println(result.toString());

但我仍然无法得到任何足够的回应。我只得到:

响应代码:400
{
"error": "invalid_request", "error_description": "无效的授权 header 。"
}

最佳答案

您需要根据 google documentation 生成有效的 oauth_signature

参见this answer生成基本字符串时的一些有用提示

POST 正文应该只包含 3 个参数,如下所示

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

关于java - 从 OAuth2.1 迁移到 OAuth2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23608326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com