2

我在使用 Google+ API OAuth2 令牌时遇到了一些问题。

这是一个获取 OAuth2 访问令牌的简单程序:

HttpClient httpclient = new HttpClient();
        PostMethod postMethod = new PostMethod("https://accounts.google.com/o/oauth2/token");
        NameValuePair[] data = {
                new NameValuePair("client_id", "API KEY HERE"),
                new NameValuePair("redirect_uri", "URL HERE"),
                new NameValuePair("client_secret", "SECRET HERE"),
                new NameValuePair("code", "CODE HERE"),
                new NameValuePair("grant_type", "authorization_code")
        };
        postMethod.setRequestBody(data);
        try {
            int result = httpclient.executeMethod(postMethod);
            assertEquals(result, 200);
            System.out.println("Response body: ");
            System.out.println(postMethod.getResponseBodyAsString());
        } catch (IOException e) {
            e.printStackTrace();
        }

这成功生成了 OAuth2 令牌。如:ya29.AHES6ZTZgptKHyZ530MoYVDPaeXvjK5DWQzPqxoNNEL2C7gsQwGfmvfT8Q

然后我设置了一个简单的测试程序,可以测试从该令牌调用 /people API:

@Test
    public void testGoogleAPIAuthdRequest() throws Exception {
        String feedUrl = "https://www.googleapis.com/plus/v1/people/me";
        String apiKey = "MY API KEY";
        String oauthCode = "OAUTH CODE FROM ABOVE";
        String jsonStr = executeGoogleFeed(feedUrl, apiKey, oauthCode).getResponseBodyAsString("UTF-8");
    }

    public Response executeGoogleFeed(String feedURL, String apiKey, String oauthCode) throws Exception {
        StringBuilder urlStr = new StringBuilder();
        urlStr.append(feedURL);
        urlStr.append("?key=");
        urlStr.append(apiKey);
        Map<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("Authorization", "Bearer " + oauthCode);
        return HttpUtil.doHttpRequest(urlStr.toString(), MethodType.GET.toString(), null,
                hashMap);
    }

这给了我一个 401 错误。没有权限。

当我转到https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=INSERT_ACCESS_TOKEN时,令牌显示为有效。

此外,当我转到https://developers.google.com/+/api/latest/people/get并从 OAuth2 登录功能获取 OAuth 令牌时......我将该 OAuth 令牌插入到我的 JUnit 测试中... 有用!

有人知道为什么我对https://accounts.google.com/o/oauth2/token的调用不能用作 Google+ api 中的 Bearer 参数吗?

4

1 回答 1

1

听起来潜在的问题是当您发送用户进行身份验证并授权您的应用程序时,您没有请求 plus.me 范围。这是在您在此处显示的内容之前的步骤中完成的,并且是返回您在上面添加的 OAuth2“代码”的组件。您可能想要更新您的示例以说明您如何获取代码以及您使用什么范围来执行此操作。

如果您正确设置范围,并且您正在使用返回的代码,则可能是您不断重复使用相同的代码。第一阶段返回的OAuth2代码只能使用一次,发出后必须非常迅速地使用。它被交换为一个具有有限生命周期的 access_token(这是您正确尝试做的)和一个具有无限生命周期的 refresh_token,用于生成新的 access_tokens。

有关用于获取和交换 OAuth2 代码的多步骤过程的完整详细信息,请参阅https://developers.google.com/accounts/docs/OAuth2WebServer 。

于 2013-04-09T13:31:54.967 回答