javaspring-bootgoogle-alloydb

What are the alternatives to using ADCs to authenticate to AlloyDB from a Spring Boot Java app?


In this thread https://www.googlecloudcommunity.com/gc/Databases/AlloyDB-ORM-Support/m-p/537212 some engineer from Google said that AlloyDb doesn't have support to spring boot natively and open sourced.

So, I can not handle use Application Default Credentials (https://cloud.google.com/docs/authentication/provide-credentials-adc#local-user-cred) and impersonate the SA.

So, Can someone confirm if i need to generates pass/user (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct) is only way to proceed (using JDBC dependencies)?

I was expecting use as cloud sql dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>spring-cloud-gcp-starter</artifactId>
</dependency>
<!-- Add CloudSQL Starter for PostgreSQL -->
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>spring-cloud-gcp-starter-sql-postgresql</artifactId>
</dependency>

Solution

  • I have a workaround: refresh a short lived SA password when is needed.

    package br.com.xyzservices.cloudSA;
    
    
    import com.google.auth.oauth2.AccessToken;
    import com.google.auth.oauth2.GoogleCredentials;
    import com.zaxxer.hikari.HikariConfig;
    import com.zaxxer.hikari.HikariDataSource;
    
    import java.io.IOException;
    
    public class CloudSqlAutoIamAuthnDataSource extends HikariDataSource {
    
        public CloudSqlAutoIamAuthnDataSource(HikariConfig configuration) {
            super(configuration);
        }
    
        @Override
        public String getPassword() {
            GoogleCredentials credentials;
            try {
                credentials = GoogleCredentials.getApplicationDefault();
    
            } catch (IOException err) {
                throw new RuntimeException(
                        "Unable to obtain credentials to communicate with the Cloud SQL API", err);
            }
    
            // Scope the token to ensure it's scoped to logins only.
            GoogleCredentials scoped = credentials.createScoped(
                    "https://www.googleapis.com/auth/sqlservice.login");
    
            try {
                scoped.refresh();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            AccessToken accessToken = scoped.getAccessToken();
            return accessToken.getTokenValue();
        }
    }
    

    Source code: https://github.com/dedeco/spring-boot-app-sa-iam-based