Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google OAuth: how to use a refresh token?

I am able to exchange my one time use token from my Android device for an access token and a refresh token. I am trying to figure out how to use the refresh token.

I found this which works over an HTTPS request, but I was wondering if there was some where in the Java SDK to handle refreshing?

like image 649
user1634451 Avatar asked Oct 21 '22 01:10

user1634451


1 Answers

You don’t need to. Just call GoogleAuthUtil.getToken() before each HTTP conversation, and GoogleAuthUtil will make sure you get one that works, refreshing if necessary.

EDITED: Oh, OK, he's doing this on the server. Here's some java code that uses a refresh token:

       String data = "refresh_token=" + mRefreshToken +
                "&client_id=" + Constants.WEB_CLIENT_ID +
                "&client_secret=" + Constants.WEB_CLIENT_SECRET +
                "&grant_type=refresh_token";
        byte[] body = data.getBytes();

        URL url = new URL(Constants.GOOGLE_TOKEN_ENDPOINT);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setFixedLengthStreamingMode(body.length);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.getOutputStream().write(body);

        body = XAuth.readStream(conn.getInputStream());
        JSONObject json = new JSONObject(new String(body));

        String accessToken = json.optString("access_token");
        if (accessToken == null) {
            throw new Exception("Refresh token yielded no access token");
        }
like image 99
Tim Bray Avatar answered Oct 31 '22 13:10

Tim Bray