com.google.api.client.auth.oauth2.StoredCredential Java Examples
The following examples show how to use
com.google.api.client.auth.oauth2.StoredCredential.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApigeeDataClient.java From apigee-android-sdk with Apache License 2.0 | 6 votes |
/** * Stores the given OAuth 2 token response within a file data store. * The stored token response can then retrieved using the getOAuth2TokenDataFromStore method. * * @param storageId a string object that is used to store the token response * @param tokenResponse the token response containing the OAuth 2 token information. * @return If the token response was stored or not. */ public Boolean storeOAuth2TokenData(String storageId, TokenResponse tokenResponse) { Boolean wasStored = false; try { File oauth2StorageFolder = new File(this.context.getFilesDir(),"oauth2StorageFolder"); oauth2StorageFolder.mkdirs(); FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(oauth2StorageFolder); DataStore<StoredCredential> storedCredentialDataStore = fileDataStoreFactory.getDataStore(storageId); Credential oauth2Credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setFromTokenResponse( tokenResponse); StoredCredential storedOAuth2Credential = new StoredCredential(oauth2Credential); storedCredentialDataStore.set(storageId,storedOAuth2Credential); wasStored = true; } catch ( Exception exception ) { logInfo("Exception storing OAuth2TokenData :" + exception.getLocalizedMessage()); } return wasStored; }
Example #2
Source File: GCalGoogleOAuth.java From openhab1-addons with Eclipse Public License 2.0 | 6 votes |
private static Credential loadCredential(String userId, DataStore<StoredCredential> credentialDataStore) throws IOException { Credential credential = newCredential(userId, credentialDataStore); if (credentialDataStore != null) { StoredCredential stored = credentialDataStore.get(userId); if (stored == null) { return null; } credential.setAccessToken(stored.getAccessToken()); credential.setRefreshToken(stored.getRefreshToken()); credential.setExpirationTimeMilliseconds(stored.getExpirationTimeMilliseconds()); if (logger.isDebugEnabled()) { logger.debug("Loaded credential"); logger.debug("device access token: {}", stored.getAccessToken()); logger.debug("device refresh_token: {}", stored.getRefreshToken()); logger.debug("device expires_in: {}", stored.getExpirationTimeMilliseconds()); } } return credential; }
Example #3
Source File: FileCredentialStoreTest.java From google-oauth-java-client with Apache License 2.0 | 6 votes |
public void testMigrateTo() throws Exception { // create old store File file = createTempFile(); FileCredentialStore store = new FileCredentialStore(file, JSON_FACTORY); Credential expected = createCredential(); store.store(USER_ID, expected); // migrate to new store File dataDir = Files.createTempDir(); dataDir.deleteOnExit(); FileDataStoreFactory newFactory = new FileDataStoreFactory(dataDir); store.migrateTo(newFactory); // check new store DataStore<StoredCredential> newStore = newFactory.getDataStore(StoredCredential.DEFAULT_DATA_STORE_ID); assertEquals(ImmutableSet.of(USER_ID), newStore.keySet()); StoredCredential actual = newStore.get(USER_ID); assertEquals(expected.getAccessToken(), actual.getAccessToken()); assertEquals(expected.getRefreshToken(), actual.getRefreshToken()); assertEquals(expected.getExpirationTimeMilliseconds(), actual.getExpirationTimeMilliseconds()); }
Example #4
Source File: AppEngineCredentialStoreTest.java From google-oauth-java-client with Apache License 2.0 | 6 votes |
public void testMigrateTo() throws Exception { // create old store AppEngineCredentialStore store = new AppEngineCredentialStore(); Credential expected = createCredential(); store.store(USER_ID, expected); // migrate to new store AppEngineDataStoreFactory newFactory = new AppEngineDataStoreFactory(); store.migrateTo(newFactory); // check new store DataStore<StoredCredential> newStore = newFactory.getDataStore(StoredCredential.DEFAULT_DATA_STORE_ID); assertEquals(ImmutableSet.of(USER_ID), newStore.keySet()); StoredCredential actual = newStore.get(USER_ID); assertEquals(expected.getAccessToken(), actual.getAccessToken()); assertEquals(expected.getRefreshToken(), actual.getRefreshToken()); assertEquals(expected.getExpirationTimeMilliseconds(), actual.getExpirationTimeMilliseconds()); }
Example #5
Source File: JPADataStore.java From sakai with Educational Community License v2.0 | 6 votes |
@Override public DataStore<StoredCredential> set(String userId, StoredCredential cred) throws IOException { GoogleDriveUser gdu = repository.findBySakaiId(userId); if(gdu == null) { gdu = new GoogleDriveUser(); gdu.setSakaiUserId(userId); gdu.setToken(cred.getAccessToken()); gdu.setRefreshToken(cred.getRefreshToken()); repository.save(gdu); } else { gdu.setToken(cred.getAccessToken()); gdu.setRefreshToken(cred.getRefreshToken()); repository.update(gdu); } return this; }
Example #6
Source File: Auth.java From youtube-chat-for-minecraft with Apache License 2.0 | 6 votes |
/** * Authorizes the installed application to access user's protected data. * * @param scopes list of scopes needed to run youtube upload. * @param clientSecret the client secret from Google API console * @param credentialDatastore name of the credential datastore to cache OAuth tokens */ public static Credential authorize( Collection<String> scopes, String clientSecret, String credentialDatastore) throws IOException { // Load client secrets GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new StringReader(clientSecret)); // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore} FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(getCredentialsDirectory())); DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes) .setCredentialDataStore(datastore) .build(); // authorize return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); }
Example #7
Source File: JPADataStore.java From sakai with Educational Community License v2.0 | 6 votes |
@Override public DataStore<StoredCredential> set(String userId, StoredCredential cred) throws IOException { GoogleDriveUser gdu = repository.findBySakaiId(userId); if(gdu == null) { gdu = new GoogleDriveUser(); gdu.setSakaiUserId(userId); gdu.setToken(cred.getAccessToken()); gdu.setRefreshToken(cred.getRefreshToken()); repository.save(gdu); } else { gdu.setToken(cred.getAccessToken()); gdu.setRefreshToken(cred.getRefreshToken()); repository.update(gdu); } return this; }
Example #8
Source File: GoogleDriveServiceImpl.java From sakai with Educational Community License v2.0 | 5 votes |
public boolean revokeGoogleDriveConfiguration(String userId){ log.info("revokeGoogleDriveConfiguration for user {}", userId); try { cleanGoogleDriveCacheForUser(userId); DataStore<StoredCredential> credentialStore = flow.getCredentialDataStore(); return (credentialStore.delete(userId) != null); } catch (Exception e) { log.warn("Error while trying to remove GoogleDrive configuration : {}", e.getMessage()); } return false; }
Example #9
Source File: ApigeeDataClient.java From apigee-android-sdk with Apache License 2.0 | 5 votes |
/** * Deletes the TokenResponse that is associated with the given storageId from the file data store. * * @param storageId The storageId associated with the stored TokenResponse. */ public void deleteStoredOAuth2TokenData(String storageId) { try { File oauth2StorageFolder = new File(this.context.getFilesDir(),"oauth2StorageFolder"); oauth2StorageFolder.mkdirs(); FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(oauth2StorageFolder); DataStore<StoredCredential> storedCredentialDataStore = fileDataStoreFactory.getDataStore(storageId); storedCredentialDataStore.delete(storageId); } catch ( Exception exception ) { logInfo("Exception deleting OAuth2TokenData :" + exception.getLocalizedMessage()); } }
Example #10
Source File: GCalGoogleOAuth.java From openhab1-addons with Eclipse Public License 2.0 | 5 votes |
private static Credential newCredential(String userId, DataStore<StoredCredential> credentialDataStore) { Credential.Builder builder = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()) .setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY) .setTokenServerEncodedUrl("https://accounts.google.com/o/oauth2/token") .setClientAuthentication(new ClientParametersAuthentication(client_id, client_secret)) .setRequestInitializer(null).setClock(Clock.SYSTEM); builder.addRefreshListener(new DataStoreCredentialRefreshListener(userId, credentialDataStore)); return builder.build(); }
Example #11
Source File: AppEngineCredentialStore.java From google-oauth-java-client with Apache License 2.0 | 5 votes |
/** * Migrates to the new format using {@link DataStore} of {@link StoredCredential}. * * @param credentialDataStore credential data store * @since 1.16 */ public final void migrateTo(DataStore<StoredCredential> credentialDataStore) throws IOException { DatastoreService service = DatastoreServiceFactory.getDatastoreService(); PreparedQuery queryResult = service.prepare(new Query(KIND)); for (Entity entity : queryResult.asIterable()) { StoredCredential storedCredential = new StoredCredential().setAccessToken( (String) entity.getProperty("accessToken")) .setRefreshToken((String) entity.getProperty("refreshToken")) .setExpirationTimeMilliseconds((Long) entity.getProperty("expirationTimeMillis")); credentialDataStore.set(entity.getKey().getName(), storedCredential); } }
Example #12
Source File: Token.java From googleads-shopping-samples with Apache License 2.0 | 5 votes |
public StoredCredential toStoredCredential() { StoredCredential credential = new StoredCredential(); credential.setAccessToken(this.getAccessToken()); credential.setRefreshToken(this.getRefreshToken()); credential.setExpirationTimeMilliseconds(this.getExpirationTimeMilliseconds()); return credential; }
Example #13
Source File: Token.java From googleads-shopping-samples with Apache License 2.0 | 5 votes |
public static Token fromStoredCredential(StoredCredential credential) { Token token = new Token(); token.setAccessToken(credential.getAccessToken()); token.setRefreshToken(credential.getRefreshToken()); token.setExpirationTimeMilliseconds(credential.getExpirationTimeMilliseconds()); return token; }
Example #14
Source File: ConfigDataStoreFactory.java From googleads-shopping-samples with Apache License 2.0 | 5 votes |
public DataStore<StoredCredential> set(String key, StoredCredential value) throws IOException { if (key != UNUSED_ID) { throw new IOException("Unexpected real user ID"); } token = Token.fromStoredCredential(value); writeToken(); return this; }
Example #15
Source File: ConfigDataStoreFactory.java From googleads-shopping-samples with Apache License 2.0 | 5 votes |
public Collection<StoredCredential> values() throws IOException { HashSet<StoredCredential> hash = new HashSet<StoredCredential>(); if (token != null) { hash.add(get(UNUSED_ID)); } return hash; }
Example #16
Source File: JPADataStore.java From sakai with Educational Community License v2.0 | 5 votes |
@Override public StoredCredential get(String userId) throws IOException { GoogleDriveUser gdu = repository.findBySakaiId(userId); if(gdu == null) { return null; } StoredCredential credential = new StoredCredential(); credential.setRefreshToken(gdu.getRefreshToken()); credential.setAccessToken(gdu.getToken()); //credential.setExpirationTimeMilliseconds(googleCredential.getExpirationTimeMilliseconds()); return credential; }
Example #17
Source File: Authorizer.java From mail-importer with Apache License 2.0 | 5 votes |
private DataStore<StoredCredential> getStoredCredentialDataStore() throws IOException { File userHomeDir = getUserHomeDir(); File mailimporter = new File(userHomeDir, ".mailimporter"); FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(mailimporter); return dataStoreFactory.getDataStore("credentials"); }
Example #18
Source File: GoogleDriveServiceImpl.java From sakai with Educational Community License v2.0 | 5 votes |
public boolean revokeGoogleDriveConfiguration(String userId){ log.info("revokeGoogleDriveConfiguration for user {}", userId); try { cleanGoogleDriveCacheForUser(userId); DataStore<StoredCredential> credentialStore = flow.getCredentialDataStore(); return (credentialStore.delete(userId) != null); } catch (Exception e) { log.warn("Error while trying to remove GoogleDrive configuration : {}", e.getMessage()); } return false; }
Example #19
Source File: JPADataStore.java From sakai with Educational Community License v2.0 | 5 votes |
@Override public StoredCredential get(String userId) throws IOException { GoogleDriveUser gdu = repository.findBySakaiId(userId); if(gdu == null) { return null; } StoredCredential credential = new StoredCredential(); credential.setRefreshToken(gdu.getRefreshToken()); credential.setAccessToken(gdu.getToken()); //credential.setExpirationTimeMilliseconds(googleCredential.getExpirationTimeMilliseconds()); return credential; }
Example #20
Source File: JPADataStore.java From sakai with Educational Community License v2.0 | 4 votes |
@Override public boolean containsValue(StoredCredential value) throws IOException { //not implemented return false; }
Example #21
Source File: LogoutCommand.java From nomulus with Apache License 2.0 | 4 votes |
@Override public void run() throws IOException { StoredCredential.getDefaultDataStore(dataStoreFactory).clear(); logger.atInfo().log("Logged out - credentials have been removed."); }
Example #22
Source File: AuthModuleTest.java From nomulus with Apache License 2.0 | 4 votes |
@Before public void setUp() throws Exception { fakeCredential.setRefreshToken(REFRESH_TOKEN); when(dataStore.get(CLIENT_ID + " scope1")).thenReturn(new StoredCredential(fakeCredential)); }
Example #23
Source File: Authorizer.java From mail-importer with Apache License 2.0 | 4 votes |
public Credential get() { try { GoogleClientSecrets clientSecrets = loadGoogleClientSecrets(jsonFactory); DataStore<StoredCredential> dataStore = getStoredCredentialDataStore(); // Allow user to authorize via url. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, jsonFactory, clientSecrets, ImmutableList.of( GmailScopes.GMAIL_MODIFY, GmailScopes.GMAIL_READONLY)) .setCredentialDataStore(dataStore) .setAccessType("offline") .setApprovalPrompt("auto") .build(); // First, see if we have a stored credential for the user. Credential credential = flow.loadCredential(user.getEmailAddress()); // If we don't, prompt them to get one. if (credential == null) { String url = flow.newAuthorizationUrl() .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI) .build(); System.out.println("Please open the following URL in your browser then " + "type the authorization code:\n" + url); // Read code entered by user. System.out.print("Code: "); System.out.flush(); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); String code = br.readLine(); // Generate Credential using retrieved code. GoogleTokenResponse response = flow.newTokenRequest(code) .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI) .execute(); credential = flow.createAndStoreCredential(response, user.getEmailAddress()); } Gmail gmail = new Gmail.Builder(httpTransport, jsonFactory, credential) .setApplicationName(GmailServiceModule.APP_NAME) .build(); Profile profile = gmail.users() .getProfile(user.getEmailAddress()) .execute(); System.out.println(profile.toPrettyString()); return credential; } catch (IOException exception) { throw new RuntimeException(exception); } }
Example #24
Source File: JPADataStore.java From sakai with Educational Community License v2.0 | 4 votes |
@Override public boolean containsValue(StoredCredential value) throws IOException { //not implemented return false; }
Example #25
Source File: FilePersistedCredentials.java From google-oauth-java-client with Apache License 2.0 | 4 votes |
void migrateTo(DataStore<StoredCredential> typedDataStore) throws IOException { for (Map.Entry<String, FilePersistedCredential> entry : credentials.entrySet()) { typedDataStore.set(entry.getKey(), entry.getValue().toStoredCredential()); } }
Example #26
Source File: FilePersistedCredential.java From google-oauth-java-client with Apache License 2.0 | 4 votes |
StoredCredential toStoredCredential() { return new StoredCredential().setAccessToken(accessToken) .setRefreshToken(refreshToken).setExpirationTimeMilliseconds(expirationTimeMillis); }
Example #27
Source File: JPADataStore.java From sakai with Educational Community License v2.0 | 4 votes |
@Override public Collection<StoredCredential> values() throws IOException { //not implemented return null; }
Example #28
Source File: JPADataStore.java From sakai with Educational Community License v2.0 | 4 votes |
@Override public DataStore<StoredCredential> clear() throws IOException { repository.deleteAll(); return this; }
Example #29
Source File: JPADataStore.java From sakai with Educational Community License v2.0 | 4 votes |
@Override public DataStore<StoredCredential> delete(String userId) throws IOException { repository.delete(userId); return this; }
Example #30
Source File: ConfigDataStoreFactory.java From googleads-shopping-samples with Apache License 2.0 | 4 votes |
public DataStore<StoredCredential> delete(String key) throws IOException { if (key.equals(UNUSED_ID)) { deleteToken(); } return this; }