Google+ api - 来自https://accounts.google.com/o/oauth2/token的密钥会出现401错误

时间:2013-04-09 12:43:22

标签: api oauth-2.0 google-plus

我在使用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参数?

1 个答案:

答案 0 :(得分:1)

听起来潜在的问题是,当您发送用户进行身份验证并授权您的应用时,您不会请求plus.me范围。这是在您在此处显示的步骤之前完成的,并且是返回您在上面添加的OAuth2“代码”的组件。您可能希望更新您的示例,以说明您如何获取代码以及您正在使用的范围。

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

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