private static OAuth2Token fromJSON(JSONObject object) throws IOException { try { return new OAuth2Token( object.getString("access_token"), object.optString("token_type", null), object.optString("refresh_token", null), object.optInt("expires_in", -1), null); } catch (JSONException e) { Log.w(TAG, "JSON parse error", e); throw new IOException("parse error"); } }
public OAuth2Token getToken(String code) throws IOException { HttpsURLConnection connection = postTokenEndpoint(getAccessTokenPostData(code)); final int responseCode = connection.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { OAuth2Token token = parseResponse(connection.getInputStream()); String username = getUsernameFromContacts(token); Log.d(TAG, "got token " + token.getTokenForLogging()+ ", username="+username); return new OAuth2Token(token.accessToken, token.tokenType, token.refreshToken, token.expiresIn, username); } else { Log.e(TAG, "error: " + responseCode); throw new IOException("Invalid response from server:" + responseCode); } }
@Test public void shouldUseOAuth2ClientWhenRefreshTokenIsPresent() throws Exception { when(authPreferences.getOauth2Token()).thenReturn("token"); when(authPreferences.getOauth2RefreshToken()).thenReturn("refresh"); when(authPreferences.getOauth2Username()).thenReturn("username"); when(oauth2Client.refreshToken("refresh")).thenReturn(new OAuth2Token("newToken", "type", null, 0, null)); refresher.refreshOAuth2Token(); verify(authPreferences).setOauth2Token("username", "newToken", "refresh"); }
@Test public void shouldUpdateRefreshTokenIfPresentInResponse() throws Exception { when(authPreferences.getOauth2Token()).thenReturn("token"); when(authPreferences.getOauth2RefreshToken()).thenReturn("refresh"); when(authPreferences.getOauth2Username()).thenReturn("username"); when(oauth2Client.refreshToken("refresh")).thenReturn(new OAuth2Token("newToken", "type", "newRefresh", 0, null)); refresher.refreshOAuth2Token(); verify(authPreferences).setOauth2Token("username", "newToken", "newRefresh"); } }
@Test public void testTokenForLogging() throws Exception { OAuth2Token token = new OAuth2Token("secret", "type", "secret", 100, "Test"); assertThat(token.getTokenForLogging()).doesNotContain("secret"); assertThat(token.toString()).doesNotContain("secret"); } }