/** * Example of creating a signed URL for the blob passing the {@link * SignUrlOption#signWith(ServiceAccountSigner)} option, that will be used to sign the URL. */ // [TARGET signUrl(long, TimeUnit, SignUrlOption...)] // [VARIABLE "/path/to/key.json"] public URL signUrlWithSigner(String keyPath) throws IOException { // [START signUrlWithSigner] URL signedUrl = blob.signUrl( 14, TimeUnit.DAYS, SignUrlOption.signWith( ServiceAccountCredentials.fromStream(new FileInputStream(keyPath)))); // [END signUrlWithSigner] return signedUrl; }
public ContainerRegistryAuthSupplier build() { final GoogleCredentials credentials = this.credentials.createScoped(scopes); // log some sort of identifier for the credentials, which requires looking at the // instance type if (credentials instanceof ServiceAccountCredentials) { final String clientEmail = ((ServiceAccountCredentials) credentials).getClientEmail(); log.info("loaded credentials for service account with clientEmail={}", clientEmail); } else if (credentials instanceof UserCredentials) { final String clientId = ((UserCredentials) credentials).getClientId(); log.info("loaded credentials for user account with clientId={}", clientId); } final Clock clock = Clock.systemDefaultZone(); final DefaultCredentialRefresher refresher = new DefaultCredentialRefresher(); return new ContainerRegistryAuthSupplier(credentials, clock, minimumExpiryMillis, refresher); } }
@Override Tuple<ServiceAccountCredentials, BlobInfo> parse(String... args) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException { if (args.length != 4) { throw new IllegalArgumentException(); } KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(Files.newInputStream(Paths.get(args[0])), PASSWORD); PrivateKey privateKey = (PrivateKey) keystore.getKey("privatekey", PASSWORD); ServiceAccountCredentials credentials = ServiceAccountCredentials.newBuilder() .setClientEmail(args[1]) .setPrivateKey(privateKey) .build(); return Tuple.of(credentials, BlobInfo.newBuilder(BlobId.of(args[2], args[3])).build()); }
private static Credentials getJwtToken(ServiceAccountCredentials serviceAccount) { return ServiceAccountJwtAccessCredentials.newBuilder() .setClientEmail(serviceAccount.getClientEmail()) .setClientId(serviceAccount.getClientId()) .setPrivateKey(serviceAccount.getPrivateKey()) .setPrivateKeyId(serviceAccount.getPrivateKeyId()) .build(); } }
@Test public void createdDelegated_clones() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = ServiceAccountCredentials.newBuilder() .setClientId(SA_CLIENT_ID) .setClientEmail(SA_CLIENT_EMAIL) .setPrivateKey(privateKey) .setPrivateKeyId(SA_PRIVATE_KEY_ID) .setScopes(SCOPES) .setServiceAccountUser(SERVICE_ACCOUNT_USER) .setProjectId(PROJECT_ID) .build(); String newServiceAccountUser = "stranger@other.org"; ServiceAccountCredentials newCredentials = (ServiceAccountCredentials) credentials.createDelegated(newServiceAccountUser); assertEquals(SA_CLIENT_ID, newCredentials.getClientId()); assertEquals(SA_CLIENT_EMAIL, newCredentials.getClientEmail()); assertEquals(privateKey, newCredentials.getPrivateKey()); assertEquals(SA_PRIVATE_KEY_ID, newCredentials.getPrivateKeyId()); assertArrayEquals(SCOPES.toArray(), newCredentials.getScopes().toArray()); assertEquals(newServiceAccountUser, newCredentials.getServiceAccountUser()); assertEquals(PROJECT_ID, newCredentials.getProjectId()); assertEquals(SERVICE_ACCOUNT_USER, ((ServiceAccountCredentials)credentials).getServiceAccountUser()); }
private static String getSignedJwt(ServiceAccountCredentials credentials, String iapClientId) throws Exception { Instant now = Instant.now(clock); long expirationTime = now.getEpochSecond() + EXPIRATION_TIME_IN_SECONDS; // generate jwt signed by service account // header must contain algorithm ("alg") and key ID ("kid") JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(credentials.getPrivateKeyId()).build(); // set required claims JWTClaimsSet claims = new JWTClaimsSet.Builder() .audience(OAUTH_TOKEN_URI) .issuer(credentials.getClientEmail()) .subject(credentials.getClientEmail()) .issueTime(Date.from(now)) .expirationTime(Date.from(Instant.ofEpochSecond(expirationTime))) .claim("target_audience", iapClientId) .build(); // sign using service account private key JWSSigner signer = new RSASSASigner(credentials.getPrivateKey()); SignedJWT signedJwt = new SignedJWT(jwsHeader, claims); signedJwt.sign(signer); return signedJwt.serialize(); }
ServiceAccountAuthCredentials(ServiceAccountCredentials credentials) { this.credentials = checkNotNull(credentials); this.account = checkNotNull(credentials.getClientEmail()); this.privateKey = checkNotNull(credentials.getPrivateKey()); }
/** * Creates an authorized Credentials object. * * @param delegatedAdminEmail A delegated admin email to associate with the created credentials. * @return An authorized Credentials object. * @throws IOException If the credentials.json file cannot be found. */ private static Credentials getCredentials(String delegatedAdminEmail) throws IOException { // [START admin_sdk_alertcenter_get_credentials] InputStream in = AdminSDKAlertCenterQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH); if (in == null) { throw new IOException("Credential file was not found"); } GoogleCredentials credentials = ServiceAccountCredentials .fromStream(in) .createDelegated(delegatedAdminEmail) .createScoped(SCOPES); // [END admin_sdk_alertcenter_get_credentials] return credentials; }
/** * Creates and returns the credentials from the given connection parameters. * * @param parameters * the connection parameters * @return the credentials for authenticating with the Datastore service. * @throws IOException * if any error occurs such as not able to read the credentials file. */ private static Credentials getCredentials(ConnectionParameters parameters) throws IOException { if (parameters.isEmulator()) { return NoCredentials.getInstance(); } InputStream jsonCredentialsStream = parameters.getJsonCredentialsStream(); if (jsonCredentialsStream != null) { return ServiceAccountCredentials.fromStream(jsonCredentialsStream); } File jsonCredentialsFile = parameters.getJsonCredentialsFile(); if (jsonCredentialsFile != null) { return ServiceAccountCredentials.fromStream(new FileInputStream(jsonCredentialsFile)); } return ServiceAccountCredentials.getApplicationDefault(); }
init(params); GoogleCredentials credentials = ServiceAccountCredentials.fromStream(new FileInputStream(keyFile)) .createScoped(Arrays.asList(new String[] { "https://www.googleapis.com/auth/cloud-platform" }));
@Override public byte[] sign(byte[] toSign) { try { Signature signer = Signature.getInstance(OAuth2Utils.SIGNATURE_ALGORITHM); signer.initSign(getPrivateKey()); signer.update(toSign); return signer.sign(); } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) { throw new SigningException("Failed to sign the provided bytes", ex); } }
@Test public void sign_sameAs() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { byte[] toSign = {0xD, 0xE, 0xA, 0xD}; ServiceAccountCredentials credentials = ServiceAccountCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, null); byte[] signedBytes = credentials.sign(toSign); Signature signature = Signature.getInstance(OAuth2Utils.SIGNATURE_ALGORITHM); signature.initSign(credentials.getPrivateKey()); signature.update(toSign); assertArrayEquals(signature.sign(), signedBytes); }
@Test public void createAssertion_correct() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); List<String> scopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials credentials = ServiceAccountCredentials.newBuilder() .setClientId(SA_CLIENT_ID) .setClientEmail(SA_CLIENT_EMAIL) .setPrivateKey(privateKey) .setPrivateKeyId(SA_PRIVATE_KEY_ID) .setScopes(scopes) .setServiceAccountUser(SERVICE_ACCOUNT_USER) .setProjectId(PROJECT_ID) .build(); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; long currentTimeMillis = Clock.SYSTEM.currentTimeMillis(); String assertion = credentials.createAssertion(jsonFactory, currentTimeMillis, null); JsonWebSignature signature = JsonWebSignature.parse(jsonFactory, assertion); JsonWebToken.Payload payload = signature.getPayload(); assertEquals(SA_CLIENT_EMAIL, payload.getIssuer()); assertEquals(OAuth2Utils.TOKEN_SERVER_URI.toString(), payload.getAudience()); assertEquals(currentTimeMillis / 1000, (long) payload.getIssuedAtTimeSeconds()); assertEquals(currentTimeMillis / 1000 + 3600, (long) payload.getExpirationTimeSeconds()); assertEquals(SERVICE_ACCOUNT_USER, payload.getSubject()); assertEquals(Joiner.on(' ').join(scopes), payload.get("scope")); }
private GoogleCredentials getSourceCredentials() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountCredentials sourceCredentials = ServiceAccountCredentials.newBuilder() .setClientEmail(SA_CLIENT_EMAIL) .setPrivateKey(privateKey) .setPrivateKeyId(SA_PRIVATE_KEY_ID) .setScopes(SCOPES) .setProjectId(PROJECT_ID) .setHttpTransportFactory(transportFactory).build(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); return sourceCredentials; }
@Override public Credentials getCredentials() throws IOException { GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); // Check if the current scopes permit JWT token use boolean hasJwtEnabledScope = false; for (String scope : getJwtEnabledScopes()) { if (getScopesToApply().contains(scope)) { hasJwtEnabledScope = true; break; } } // Use JWT tokens when using a service account with an appropriate scope. if (credentials instanceof ServiceAccountCredentials && hasJwtEnabledScope) { ServiceAccountCredentials serviceAccount = (ServiceAccountCredentials) credentials; return ServiceAccountJwtAccessCredentials.newBuilder() .setClientEmail(serviceAccount.getClientEmail()) .setClientId(serviceAccount.getClientId()) .setPrivateKey(serviceAccount.getPrivateKey()) .setPrivateKeyId(serviceAccount.getPrivateKeyId()) .build(); } if (credentials.createScopedRequired()) { credentials = credentials.createScoped(getScopesToApply()); } return credentials; }
@Test public void createdScoped_clones() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() .setClientId(SA_CLIENT_ID) .setClientEmail(SA_CLIENT_EMAIL) .setPrivateKey(privateKey) .setPrivateKeyId(SA_PRIVATE_KEY_ID) .setScopes(SCOPES) .setServiceAccountUser(SERVICE_ACCOUNT_USER) .setProjectId(PROJECT_ID) .build(); List<String> newScopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials newCredentials = (ServiceAccountCredentials) credentials.createScoped(newScopes); assertEquals(SA_CLIENT_ID, newCredentials.getClientId()); assertEquals(SA_CLIENT_EMAIL, newCredentials.getClientEmail()); assertEquals(privateKey, newCredentials.getPrivateKey()); assertEquals(SA_PRIVATE_KEY_ID, newCredentials.getPrivateKeyId()); assertArrayEquals(newScopes.toArray(), newCredentials.getScopes().toArray()); assertEquals(SERVICE_ACCOUNT_USER, newCredentials.getServiceAccountUser()); assertEquals(PROJECT_ID, newCredentials.getProjectId()); assertArrayEquals(SCOPES.toArray(), ((ServiceAccountCredentials)credentials).getScopes().toArray()); }
/** * Creates Service Account Credentials given a stream for credentials in JSON format. * * <p>For details on how to obtain Service Account Credentials in JSON format see * <a href="https://cloud.google.com/storage/docs/authentication?hl=en#service_accounts">Service * Account Authentication</a>. * </p> * * @param jsonCredentialStream stream for Service Account Credentials in JSON format * @return the credentials instance * @throws IOException if the credentials cannot be created from the stream */ public static ServiceAccountAuthCredentials createForJson(InputStream jsonCredentialStream) throws IOException { GoogleCredentials tempCredentials = GoogleCredentials.fromStream(jsonCredentialStream); if (tempCredentials instanceof ServiceAccountCredentials) { ServiceAccountCredentials tempServiceAccountCredentials = (ServiceAccountCredentials) tempCredentials; return new ServiceAccountAuthCredentials( tempServiceAccountCredentials.getClientEmail(), tempServiceAccountCredentials.getPrivateKey()); } throw new IOException( "The given JSON Credentials Stream is not for a service account credential."); } }
@Override public byte[] sign(byte[] toSign) { try { Signature signer = Signature.getInstance(OAuth2Utils.SIGNATURE_ALGORITHM); signer.initSign(getPrivateKey()); signer.update(toSign); return signer.sign(); } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) { throw new SigningException("Failed to sign the provided bytes", ex); } }
@Test public void createAssertion_withTokenUri_correct() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); List<String> scopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials credentials = ServiceAccountCredentials.newBuilder() .setClientId(SA_CLIENT_ID) .setClientEmail(SA_CLIENT_EMAIL) .setPrivateKey(privateKey) .setPrivateKeyId(SA_PRIVATE_KEY_ID) .setScopes(scopes) .setServiceAccountUser(SERVICE_ACCOUNT_USER) .setProjectId(PROJECT_ID) .build(); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; long currentTimeMillis = Clock.SYSTEM.currentTimeMillis(); String assertion = credentials.createAssertion(jsonFactory, currentTimeMillis, "https://foo.com/bar"); JsonWebSignature signature = JsonWebSignature.parse(jsonFactory, assertion); JsonWebToken.Payload payload = signature.getPayload(); assertEquals(SA_CLIENT_EMAIL, payload.getIssuer()); assertEquals("https://foo.com/bar", payload.getAudience()); assertEquals(currentTimeMillis / 1000, (long) payload.getIssuedAtTimeSeconds()); assertEquals(currentTimeMillis / 1000 + 3600, (long) payload.getExpirationTimeSeconds()); assertEquals(SERVICE_ACCOUNT_USER, payload.getSubject()); assertEquals(Joiner.on(' ').join(scopes), payload.get("scope")); }
private Subscriber createSubscriberWithCustomCredentials() throws Exception { // [START pubsub_subscriber_custom_credentials] CredentialsProvider credentialsProvider = FixedCredentialsProvider.create( ServiceAccountCredentials.fromStream(new FileInputStream("credentials.json"))); Subscriber subscriber = Subscriber.newBuilder(subscriptionName, receiver) .setCredentialsProvider(credentialsProvider) .build(); // [END pubsub_subscriber_custom_credentials] return subscriber; }