【问题标题】:OAuth token invalid_grantOAuth 令牌 invalid_grant
【发布时间】:2014-10-18 20:34:26
【问题描述】:

我正在尝试将 Google Plus API 集成到我的网络应用程序中。

我能够通过 Google 进行身份验证并获得代码。当我尝试使用HttpClient 获取access_token 时出现问题。

这里有一些代码:

DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "https://accounts.google.com/o/oauth2/token");
        post.addHeader("accept", "application/json");
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("code", myCode));
        nvps.add(new BasicNameValuePair("client_id",
                "my_client_id"));
        nvps.add(new BasicNameValuePair("redirect_uri",
                "http://localhost:8080/test/gplus.do"));
        nvps.add(new BasicNameValuePair("client_secret",
                "my_client_secret"));
        nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
        post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse response = httpClient.execute(post);

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

        String output;
        while ((output = br.readLine()) != null) {
            res = res + output;
        }

我之前曾多次设法在我的模拟应用程序中获取令牌,但现在它似乎由于某种未知原因而失败。我得到的只是error:invalid_grant。为什么会这样?

【问题讨论】:

    标签: java oauth oauth-2.0


    【解决方案1】:

    你确定你以前通过这种方式获得过令牌吗? AFAIK,在 oAuth 中,您首先调用 /authorize 以获取授权码,然后使用此代码调用 /token 以获取访问令牌。

    附言您可以将包用作Spring for oAuth,因此它可以制作所有“幕后”的东西,您所要做的就是配置XML。

    【讨论】:

    • 是的,我之前得到了令牌。更重要的是,我确实得到了代码,但是在尝试用它交换令牌时出现了问题。我不会使用任何库,但如果问题仍然存在,我会看看你建议的那个。
    • 所以第一个调用 (/authorize) 正在工作,但第二个调用失败。 1. 你看到的错误是什么? 2. 尝试调试到 HttpClient 并查看您尝试发送到服务器的 URL。然后,使用 REST-client 并尝试使用相同的 URL(我们尝试查明问题...)
    • 问题是我使用httpclient发出请求,但不知何故我被重定向到我的redirect_uri,这让我再次调用令牌。这是我收到错误的时候。你能告诉我应该怎么做吗?
    • 我想到的最简单的事情 - 当您被重定向回您的 URI 时,请检查令牌。如果存在 - 不要再次调用 /token。 o/w - 请求令牌。 HTH...
    • 显然问题出在我的代码的另一部分。我没有使用我应该使用的一些方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 2015-05-30
    • 2017-05-16
    • 1970-01-01
    • 2015-09-04
    相关资源
    最近更新 更多