Credential credential = newFlow().loadCredential(userId); if (credential.getRefreshToken() != null) { logger.log(Level.SEVERE, "Refresh token is not null"); } else { logger.log(Level.SEVERE, "Refresh token is null!"); }
public void store(Credential credential) { this.credential = Optional.of(credential); Properties properties = new Properties(); properties.setProperty(PROP_ACCESS_TOKEN, credential.getAccessToken()); properties.setProperty(PROP_REFRESH_TOKEN, credential.getRefreshToken()); try { File file = getAuthenticationFile(options); properties.store(new FileWriter(file), "Properties of jdrivesync."); } catch (IOException e) { throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to store properties file: " + e.getMessage(), e); } }
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE); @Override public Credential authorize() throws IOException { InputStream in = DriveQuickstartImpl.class.getResourceAsStream("/client_secret.json"); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) .setDataStoreFactory(DATA_STORE_FACTORY) .setAccessType("online").setApprovalPrompt("auto") .build(); Credential credential = new AuthorizationCodeInstalledApp( flow, new LocalServerReceiver()).authorize("user"); if(credential!=null && credential.getRefreshToken() != null){ storeCredentials(credential); } return credential; }
/** * Store information from the credential. * * @param credential credential whose {@link Credential#getAccessToken access token}, * {@link Credential#getRefreshToken refresh token}, and * {@link Credential#getExpirationTimeMilliseconds expiration time} need to be stored */ void store(Credential credential) { accessToken = credential.getAccessToken(); refreshToken = credential.getRefreshToken(); expirationTimeMillis = credential.getExpirationTimeMilliseconds(); }
/** * Store information from the credential. * * @param credential credential whose {@link Credential#getAccessToken access token}, * {@link Credential#getRefreshToken refresh token}, and * {@link Credential#getExpirationTimeMilliseconds expiration time} need to be stored */ void store(Credential credential) { accessToken = credential.getAccessToken(); refreshToken = credential.getRefreshToken(); expirationTimeMillis = credential.getExpirationTimeMilliseconds(); }
/** * Creates offline-friendly auth object using a credential object. * * Use this method when your application has already performed the oauth * flow and needs to store and use the credential later in an offline * manner (e.g., via Google Cloud Dataflow). * * @param credential The credential to be used for requests. */ public OfflineAuth(Credential credential) { Preconditions.checkNotNull(credential); ClientParametersAuthentication clientParams = (ClientParametersAuthentication) credential.getClientAuthentication(); this.clientId = clientParams.getClientId(); this.clientSecret = clientParams.getClientSecret(); this.refreshToken = credential.getRefreshToken(); }
@Override public void store(String userId, Credential credential) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity entity = new Entity(KIND, userId); entity.setProperty("accessToken", credential.getAccessToken()); entity.setProperty("refreshToken", credential.getRefreshToken()); entity.setProperty("expirationTimeMillis", credential.getExpirationTimeMilliseconds()); datastore.put(entity); }
public void store(String userId, Credential credential) throws IOException { Session session = persistence.getSession(table.getDatabaseName()); Column idColumn = DatabaseLogic.findColumnByPropertyName(table, idProperty); Object idValue = OgnlUtils.convertValue(userId, idColumn.getActualJavaType()); Criteria criteria = session.createCriteria(table.getActualEntityName()).add(Restrictions.eq(idProperty, idValue)); TableAccessor tableAccessor = new TableAccessor(table); Object record = criteria.uniqueResult(); boolean isNew = record == null; if(isNew) { record = create(tableAccessor, idValue); } try { tableAccessor.getProperty(accessTokenProperty).set(record, credential.getAccessToken()); tableAccessor.getProperty(refreshTokenProperty).set(record, credential.getRefreshToken()); PropertyAccessor exp = tableAccessor.getProperty(expirationProperty); exp.set(record, OgnlUtils.convertValue(credential.getExpirationTimeMilliseconds(), exp.getType())); } catch (NoSuchFieldException e) { throw new Error(e); } if(isNew) { session.save(table.getActualEntityName(), record); } else { session.update(table.getActualEntityName(), record); } session.getTransaction().commit(); session.beginTransaction(); }
public void store(String userId, Credential credential) throws IOException { Session session = persistence.getSession(table.getDatabaseName()); Column idColumn = DatabaseLogic.findColumnByPropertyName(table, idProperty); Object idValue = OgnlUtils.convertValue(userId, idColumn.getActualJavaType()); Criteria criteria = session.createCriteria(table.getActualEntityName()).add(Restrictions.eq(idProperty, idValue)); TableAccessor tableAccessor = new TableAccessor(table); Object record = criteria.uniqueResult(); boolean isNew = record == null; if(isNew) { record = create(tableAccessor, idValue); } try { tableAccessor.getProperty(accessTokenProperty).set(record, credential.getAccessToken()); tableAccessor.getProperty(refreshTokenProperty).set(record, credential.getRefreshToken()); PropertyAccessor exp = tableAccessor.getProperty(expirationProperty); exp.set(record, OgnlUtils.convertValue(credential.getExpirationTimeMilliseconds(), exp.getType())); } catch (NoSuchFieldException e) { throw new Error(e); } if(isNew) { session.save(table.getActualEntityName(), record); } else { session.update(table.getActualEntityName(), record); } session.getTransaction().commit(); session.beginTransaction(); }
private static Credentials getUserCredentials(String credentialsPath, List<String> selectedScopes) throws IOException, GeneralSecurityException { GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( JSON_FACTORY, new InputStreamReader(new FileInputStream(credentialsPath))); String clientId = clientSecrets.getDetails().getClientId(); String clientSecret = clientSecrets.getDetails().getClientSecret(); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, selectedScopes) .setDataStoreFactory(new FileDataStoreFactory(DATA_STORE_DIR)) .setAccessType("offline") .build(); LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(LOCAL_RECEIVER_PORT).build(); Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); return UserCredentials.newBuilder() .setClientId(clientId) .setClientSecret(clientSecret) .setRefreshToken(credential.getRefreshToken()) .build(); } }
public OneDriveCredential(Credential credential, String businessResource) { super(new Credential.Builder(credential.getMethod()).setTransport(credential.getTransport()) .setJsonFactory(credential.getJsonFactory()) .setTokenServerEncodedUrl( credential.getTokenServerEncodedUrl()) .setClientAuthentication( credential.getClientAuthentication()) .setRequestInitializer(credential.getRequestInitializer()) .setRefreshListeners(credential.getRefreshListeners()) .setClock(credential.getClock())); setAccessToken(credential.getAccessToken()); setRefreshToken(credential.getRefreshToken()); setExpirationTimeMilliseconds(credential.getExpirationTimeMilliseconds()); this.businessResource = Objects.requireNonNull(businessResource); }
assertEquals("newRefreshToken", credential.getRefreshToken());
/** * Authorizes the installed application to access user's protected data. * * @param userId user ID or {@code null} if not using a persisted credential store * @return credential */ public Credential authorize(String userId) throws IOException { try { Credential credential = flow.loadCredential(userId); if (credential != null && (credential.getRefreshToken() != null || credential.getExpiresInSeconds() == null || credential.getExpiresInSeconds() > 60)) { return credential; } // open in browser String redirectUri = receiver.getRedirectUri(); AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUri); onAuthorization(authorizationUrl); // receive authorization code and exchange it for an access token String code = receiver.waitForCode(); TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute(); // store credential and return it return flow.createAndStoreCredential(response, userId); } finally { receiver.stop(); } }
@Test public void loadCredential() throws Exception { OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("http://redirect") .setHttpTransport(mockHttpTransport) .setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST)) .build(); oAuth2Credentials.authenticate("authorizationCode", "userId"); Credential credential = oAuth2Credentials.loadCredential("userId"); assertEquals("Refresh token does not match.", "refreshToken", credential.getRefreshToken()); assertTrue("Expected expires_in between 0 and 3600. Was actually: " + credential.getExpiresInSeconds(), credential.getExpiresInSeconds() > 0 && credential.getExpiresInSeconds() <= 3600); assertEquals("Access token does not match.", "accessToken", credential.getAccessToken()); assertEquals("Access method (Bearer) does not match", BearerToken.authorizationHeaderAccessMethod().getClass(), credential.getMethod().getClass()); }
/** * Tests that the builder builds and gets an OAuth2 token correctly. */ @Test public void testGenerateCredential() throws Exception { testHttpServer.setMockResponseBody( "{\"access_token\" : \"accessToken\"," + "\"token_type\" : \"Bearer\"," + "\"expires_in\" : 3600," + "\"refresh_token\" : \"newRefreshToken\"}"); OfflineCredentials offlineCredentials = new OfflineCredentials.Builder() .forApi(OfflineCredentials.Api.AD_MANAGER) .withTokenUrlServer(testHttpServer.getServerUrl()) .withClientSecrets("clientId", "clientSecret") .withRefreshToken("refreshToken") .build(); Credential credential = offlineCredentials.generateCredential(); assertTrue(testHttpServer.getLastRequestBody().contains("grant_type=refresh_token")); assertTrue(testHttpServer.getLastRequestBody().contains("refresh_token=refreshToken")); assertTrue(testHttpServer.getLastRequestBody().contains("client_id=clientId")); assertTrue(testHttpServer.getLastRequestBody().contains("client_secret=clientSecret")); assertEquals("accessToken", credential.getAccessToken()); assertEquals("newRefreshToken", credential.getRefreshToken()); }
@Test public void authenticate() throws Exception { String authorizationCode = "authorizationCode"; String expectedRequestContent = "code=authorizationCode&grant_type=authorization_code" + "&redirect_uri=http%3A%2F%2Fredirect&scope=profile+request" + "&client_id=CLIENT_ID&client_secret=CLIENT_SECRET"; OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("http://redirect") .setHttpTransport(mockHttpTransport) .setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST)) .build(); Credential credential = oAuth2Credentials.authenticate(authorizationCode, "userId"); assertEquals("Request URL did not match.", TOKEN_REQUEST_URL, mockHttpTransport.lastRequestUrl); assertEquals("Request content did not match.", expectedRequestContent, mockHttpTransport.lastRequestContent); assertEquals("Refresh token does not match.", "refreshToken", credential.getRefreshToken()); assertTrue("Expected expires_in between 0 and 3600. Was actually: " + credential.getExpiresInSeconds(), credential.getExpiresInSeconds() > 0 && credential.getExpiresInSeconds() <= 3600); assertEquals("Access token does not match.", "accessToken", credential.getAccessToken()); assertEquals("Access method (Bearer) does not match", BearerToken.authorizationHeaderAccessMethod().getClass(), credential.getMethod().getClass()); }
Credential loadedCredential = oAuth2Credentials.loadCredential("userId"); assertEquals("Refresh token does not match.", "refreshToken", storedCredential.getRefreshToken()); assertTrue("Expected expires_in between 0 and 3600. Was actually: " + storedCredential.getExpiresInSeconds(), storedCredential.getExpiresInSeconds() > 0 && storedCredential.getExpiresInSeconds() <= 3600); BearerToken.authorizationHeaderAccessMethod().getClass(), storedCredential.getMethod().getClass()); assertEquals("Refresh token does not match.", "refreshToken2", loadedCredential.getRefreshToken()); assertTrue("Expected expires_in between 0 and 1000. Was actually: " + loadedCredential.getExpiresInSeconds(), loadedCredential.getExpiresInSeconds() > 0 && loadedCredential.getExpiresInSeconds() <= 1000L);
/** * Tests generating OAuth2 credentials. */ @Test public void testGenerateCredential_defaultTransport() throws Exception { OfflineCredentials offlineCredentials = new OfflineCredentials.Builder(oAuth2Helper) .forApi(OfflineCredentials.Api.AD_MANAGER) .withClientSecrets("clientId", "clientSecret") .withRefreshToken("refreshToken") .build(); when(oAuth2Helper.callRefreshToken(Mockito.<Credential>anyObject())).thenReturn(true); Credential credential = offlineCredentials.generateCredential(); assertEquals( "clientId", ((ClientParametersAuthentication) credential.getClientAuthentication()).getClientId()); assertEquals( "clientSecret", ((ClientParametersAuthentication) credential.getClientAuthentication()).getClientSecret()); assertEquals("refreshToken", credential.getRefreshToken()); assertSame(ForApiBuilder.DEFAULT_HTTP_TRANSPORT, credential.getTransport()); }
@Test public void authenticate_whenThereAreNoScopes() throws Exception { String authorizationCode = "authorizationCode"; String expectedRequestContent = "code=authorizationCode&grant_type=authorization_code" + "&redirect_uri=http%3A%2F%2Fredirect" + "&client_id=CLIENT_ID&client_secret=CLIENT_SECRET"; OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("http://redirect") .setHttpTransport(mockHttpTransport) .build(); Credential credential = oAuth2Credentials.authenticate(authorizationCode, "userId"); assertEquals("Request URL did not match.", TOKEN_REQUEST_URL, mockHttpTransport.lastRequestUrl); assertEquals("Request content did not match.", expectedRequestContent, mockHttpTransport.lastRequestContent); assertEquals("Refresh token does not match.", "refreshToken", credential.getRefreshToken()); assertTrue("Expected expires_in between 0 and 3600. Was actually: " + credential.getExpiresInSeconds(), credential.getExpiresInSeconds() > 0 && credential.getExpiresInSeconds() <= 3600); assertEquals("Access token does not match.", "accessToken", credential.getAccessToken()); assertEquals("Access method (Bearer) does not match", BearerToken.authorizationHeaderAccessMethod().getClass(), credential.getMethod().getClass()); }
/** * Tests generating OAuth2 credentials. */ @Test public void testGenerateCredential() throws Exception { HttpTransport httpTransport = new NetHttpTransport(); OfflineCredentials offlineCredentials = new OfflineCredentials.Builder(oAuth2Helper) .forApi(OfflineCredentials.Api.AD_MANAGER) .withClientSecrets("clientId", "clientSecret") .withRefreshToken("refreshToken") .withHttpTransport(httpTransport) .build(); when(oAuth2Helper.callRefreshToken(Mockito.<Credential>anyObject())).thenReturn(true); Credential credential = offlineCredentials.generateCredential(); assertEquals( "clientId", ((ClientParametersAuthentication) credential.getClientAuthentication()).getClientId()); assertEquals( "clientSecret", ((ClientParametersAuthentication) credential.getClientAuthentication()).getClientSecret()); assertEquals("refreshToken", credential.getRefreshToken()); assertSame(httpTransport, credential.getTransport()); }