/** * Ensure the client secrets file has been filled out. * * @param clientSecrets the GoogleClientSecrets containing data from the * file */ private static void checkClientSecretsFile( GoogleClientSecrets clientSecrets ) { if ( clientSecrets.getDetails().getClientId().startsWith( "[[INSERT" ) || clientSecrets.getDetails().getClientSecret().startsWith( "[[INSERT" ) ) { LOG.error( "Enter Client ID and Secret from " + "APIs console into resources/client_secrets.json." ); System.exit( 1 ); } }
private static Credential authorizeWithServiceAccount( String serviceAccountEmail, File pk12File ) throws GeneralSecurityException, IOException { LOG.info( String.format( "Authorizing using Service Account: %s", serviceAccountEmail ) ); // Build service account credential. GoogleCredential credential = new GoogleCredential.Builder() .setTransport( httpTransport ) .setJsonFactory( JSON_FACTORY ) .setServiceAccountId( serviceAccountEmail ) .setServiceAccountScopes( Collections.singleton( AndroidPublisherScopes.ANDROIDPUBLISHER ) ) .setServiceAccountPrivateKeyFromP12File( pk12File == null ? new File( SRC_RESOURCES_KEY_P12 ) : pk12File ) .build(); return credential; }
private static Credential buildCredentialFromJson(String privateKeyPath, Optional<String> fsUri, HttpTransport transport, Collection<String> serviceAccountScopes) throws IOException { FileSystem fs = getFileSystem(fsUri); Path keyPath = getPrivateKey(fs, privateKeyPath); return GoogleCredential.fromStream(fs.open(keyPath), transport, JSON_FACTORY) .createScoped(serviceAccountScopes); }
private Credential authorize() throws IOException { InputStream in = new FileInputStream( resolveCredentialsPath() + "/" + resourceBundle.getString( "client.secrets" ) ); 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( "offline" ).build(); Credential credential = new CustomAuthorizationCodeInstalledApp( flow, new CustomLocalServerReceiver() ).authorize( "user" ); return credential; }
@Inject GoogleAppSecretDecrypter( HttpTransport transport, JsonFactory jsonFactory, @ProjectId String projectId) throws GoogleCredentialException { GoogleCredential credential; try { credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); } catch (IOException e) { throw new GoogleCredentialException( "Problem obtaining credentials via GoogleCredential.getApplicationDefault()"); } if (credential.createScopedRequired()) { credential = credential.createScoped(CloudKMSScopes.all()); } this.cloudKMS = new CloudKMS.Builder(transport, jsonFactory, credential) .setApplicationName("GoogleAppSecretDecrypter") .build(); this.secretsCryptoKey = String.format(SECRETS_CRYPTO_KEY_FMT_STRING, projectId); }
String[] SCOPESArray = {"https://spreadsheets.google.com/feeds", "https://spreadsheets.google.com/feeds/spreadsheets/private/full", "https://docs.google.com/feeds"}; final List SCOPES = Arrays.asList(SCOPESArray); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(jsonFactory)
Credential credential = GoogleCredential.getApplicationDefault(); if (serviceAccountEmail != null && privateKeyFile != null) { credential = DatastoreHelper.getServiceAccountCredential( logger.info("Using default gcloud credential."); logger.info("DatasetID: " + datasetId + ", Service Account Email: " + ((GoogleCredential) credential).getServiceAccountId());
HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(jsonFactory) .setClientSecrets("client_id", "client_secret").build(); credential.setAccessToken("access_token");
private Subject buildSubject(String accessToken, GoogleIdToken.Payload payload) { TokenCredential.Builder builder = TokenCredential.builder(); builder.issueTime(toInstant(payload.getIssuedAtTimeSeconds())); builder.expTime(toInstant(payload.getExpirationTimeSeconds())); builder.issuer(payload.getIssuer()); builder.token(accessToken); builder.addToken(GoogleIdToken.Payload.class, payload); String email = payload.getEmail(); String userId = payload.getSubject(); Principal principal = Principal.builder() .id(userId) .name((null == email) ? userId : email) .addAttribute("fullName", payload.get("name")) .addAttribute("emailVerified", payload.getEmailVerified()) .addAttribute("locale", payload.get("locale")) .addAttribute("familyName", payload.get("family_name")) .addAttribute("givenName", payload.get("given_name")) .addAttribute("pictureUrl", payload.get("picture")) .build(); return Subject.builder() .principal(principal) .addPublicCredential(TokenCredential.class, builder.build()) .build(); }
private Optional<CachedRecord> verifyGoogle(String accessToken, GoogleIdToken token, Tracer tracer, SpanContext tracingSpan) throws SecurityException { Span span = tracer.buildSpan("googleTokenVerification") .asChildOf(tracingSpan) .start(); try { if (verifier.verify(token)) { return Optional.of(new CachedRecord(buildSubject(accessToken, token.getPayload()), () -> !verifyLocal(token.getPayload()))); } else { return Optional.empty(); } } catch (GeneralSecurityException | IOException e) { throw new SecurityException("Failed to verify Google token", e); } finally { span.finish(); } }
this.verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory) .setAudience(CollectionsHelper.setOf(clientId)) .build(); } catch (Exception e) { throw new GoogleTokenException("Failed to initialize transport", e); this.tokenParser = (jsonFactory, token) -> { try { return GoogleIdToken.parse(jsonFactory, token); } catch (IOException e) { throw new SecurityException("Failed to parse Google token", e);
private AuthenticationResponse cachedResponse(String token, Tracer tracer, SpanContext tracingSpan) { try { GoogleIdToken gToken = tokenParser.apply(jsonFactory, token); GoogleIdToken.Payload payload = gToken.getPayload(); // validate timeout if (verifyLocal(payload)) { return subjectCache.computeValue(token, () -> verifyGoogle(token, gToken, tracer, tracingSpan)) .map(CachedRecord::getSubject) .map(AuthenticationResponse::success) .orElseGet(() -> fail(null)); } else { subjectCache.remove(token); return fail(null); } } catch (SecurityException e) { if (e.getCause() instanceof IOException) { return failInvalidRequest((IOException) e.getCause()); } return fail(e.getCause()); } catch (Exception e) { return fail(e); } }
private boolean verifyLocal(GoogleIdToken.Payload payload) { Long issueTime = payload.getIssuedAtTimeSeconds(); Long expiryTime = payload.getExpirationTimeSeconds(); long currentTime = TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS); if (null != issueTime) { // lowest allowed time long checkTime = currentTime + TIME_SKEW_SECONDS; if (issueTime > checkTime) { LOGGER.log(Level.FINEST, () -> "Token pre-validation failed, issue time too late: " + issueTime + " for " + payload); return false; } } if (null != expiryTime) { long checkTime = currentTime - TIME_SKEW_SECONDS; if (expiryTime < checkTime) { LOGGER.log(Level.FINEST, () -> "Token pre-validation failed, expiration time too early: " + expiryTime + " for " + payload); return false; } } return true; }
public GoogleAnalyticsApiFacade( HttpTransport httpTransport, JsonFactory jsonFactory, String application, String oathServiceEmail, File keyFile ) throws IOException, GeneralSecurityException { Assert.assertNotNull( httpTransport, "HttpTransport cannot be null" ); Assert.assertNotNull( jsonFactory, "JsonFactory cannot be null" ); Assert.assertNotBlank( application, "Application name cannot be empty" ); Assert.assertNotBlank( oathServiceEmail, "OAuth Service Email name cannot be empty" ); Assert.assertNotNull( keyFile, "OAuth secret key file cannot be null" ); this.httpTransport = httpTransport; Credential credential = new GoogleCredential.Builder() .setTransport( httpTransport ) .setJsonFactory( jsonFactory ) .setServiceAccountScopes( AnalyticsScopes.all() ) .setServiceAccountId( oathServiceEmail ) .setServiceAccountPrivateKeyFromP12File( keyFile ) .build(); analytics = new Analytics.Builder( httpTransport, jsonFactory, credential ) .setApplicationName( application ) .build(); }
@Provides @LazySingleton public GoogleStorage getGoogleStorage(final GoogleAccountConfig config) throws IOException, GeneralSecurityException { LOG.info("Building Cloud Storage Client..."); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory); if (credential.createScopedRequired()) { credential = credential.createScoped(StorageScopes.all()); } Storage storage = new Storage.Builder(httpTransport, jsonFactory, credential).setApplicationName(APPLICATION_NAME).build(); return new GoogleStorage(storage); } }
tokenResponse.setTokenType("Bearer"); HttpRequestInitializer credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT) .setJsonFactory(JSON_FACTORY) .setClientSecrets(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET)
localCopied.deleteOnExit(); try { return new GoogleCredential.Builder() .setTransport(transport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(id.get()) .setServiceAccountPrivateKeyFromP12File(localCopied) .setServiceAccountScopes(serviceAccountScopes) .build(); } finally { boolean isDeleted = localCopied.delete();
GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY) .setServiceAccountId(confBean.getServiceAccountId()).setServiceAccountScopes("https://spreadsheets.google.com/feeds") .setServiceAccountPrivateKeyFromP12File(new File("path to the P12File")) .setServiceAccountUser("user@domain.com") .build(); SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1"); service.setOAuth2Credentials(credential);
new GoogleCredential.Builder() .setTransport(this.httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(service_acct_email) .setServiceAccountScopes(scopes) .setServiceAccountPrivateKeyFromP12File(gcsPrivateKeyHandle) .build();
cred = new GoogleCredential.Builder().setTransport(httpTransport) .setJsonFactory(JacksonFactory.getDefaultInstance()).setServiceAccountId(srvcAccountId) .setServiceAccountPrivateKeyFromP12File(new File(srvcAccountP12FilePath)) .setServiceAccountScopes(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL)).build();