GoogleAuthenticator extends AbstractOAuth2Authenticator { @Override protected OAuth2User loadUserIdentity(final OAuth2IdPToken token) { Response r = getClient() .target("https: .request() .header(HttpHeaders.AUTHORIZATION, HttpUtil.authHeaderBearer(token.getAccessToken())) .get(); try { if (r.getStatusInfo().getFamily().equals(Family.SUCCESSFUL)) { GoogleUserEntity gUser = r.readEntity(GoogleUserEntity.class); if (Strings.isNullOrEmpty(gUser.getId())) { throw new ThirdPartyErrorException(); } return gUser.asGenericUser(); } else { Map<String, String> params = r.readEntity(MAP_TYPE); throw new ThirdPartyErrorException(params); } } catch (ProcessingException e) { throw new ThirdPartyErrorException(); } finally { r.close(); } }    }
@Test public void testLoadUser() { OAuth2IdPToken result = new OAuth2IdPToken(); result.setAccessToken("google_access_token"); GoogleUserEntity user = new GoogleUserEntity(); user.setId("test_id"); user.setName("test name"); doReturn(user).when(getResponse).readEntity(GoogleUserEntity.class); OAuth2User returnedUser = googleAuth.loadUserIdentity(result); assertEquals(returnedUser.getId(), user.getId()); assertEquals("test name", returnedUser.getClaims().get("name")); }
@Test(expected = ThirdPartyErrorException.class) public void testLoadUserWithRemoteError() { OAuth2IdPToken result = new OAuth2IdPToken(); result.setAccessToken("google_access_token"); Map<String, String> response = new HashMap<>(); response.put("error", "test"); response.put("error_description", "description"); doReturn(Status.BAD_REQUEST).when(getResponse).getStatusInfo(); doReturn(response).when(getResponse) .readEntity(GoogleAuthenticator.MAP_TYPE); googleAuth.loadUserIdentity(result); }
@Test(expected = ThirdPartyErrorException.class) public void testLoadUserUnparseable() { OAuth2IdPToken result = new OAuth2IdPToken(); result.setAccessToken("google_access_token"); doThrow(ProcessingException.class) .when(getResponse).readEntity(GoogleUserEntity.class); googleAuth.loadUserIdentity(result); }
@Test(expected = ThirdPartyErrorException.class) public void testLoadUserNoResponse() { OAuth2IdPToken idPToken = new OAuth2IdPToken(); idPToken.setAccessToken("google_access_token"); GoogleUserEntity result = new GoogleUserEntity(); doReturn(result).when(getResponse).readEntity(GoogleUserEntity.class); googleAuth.loadUserIdentity(idPToken); }
@Test(expected = Exception.class) public void testLoadUserErrorOnClose() { OAuth2IdPToken idPToken = new OAuth2IdPToken(); idPToken.setAccessToken("google_access_token"); GoogleUserEntity testUser = new GoogleUserEntity(); testUser.setId(RandomStringUtils.randomAlphanumeric(10)); testUser.setName("Some Random Name"); testUser.setEmail("lol@example.com"); doReturn(testUser).when(getResponse) .readEntity(GoogleUserEntity.class); doThrow(Exception.class).when(getResponse).close(); MultivaluedStringMap params = new MultivaluedStringMap(); params.putSingle("code", "valid_code"); googleAuth.loadUserIdentity(idPToken); }