简体   繁体   中英

OAuth token invalid_grant

I am trying to integrate the Google Plus API into my web application.

I am able to authenticate with Google and I get the code. The problem occurs when I try getting an access_token using HttpClient .

Here is some code:

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;
        }

I have managed to get the token in my mock application several times before, but now it seems to be failing for some unknown reason. All I get is error:invalid_grant . Why is this happening?

are you sure u got the token this way before? AFAIK, in oAuth, you first call /authorize to get the authorization code, and then, using this code, you make the call to /token to get the access token.

ps you can use packages as Spring for oAuth , so it makes all the "behind-the-scenes" stuff, all you have to do is to configure the XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM