Log in using IAM database authentication Stay organized with collections Save and categorize content based on your preferences.
This page describes how users and service accounts can log in to Cloud SQLdatabases using Cloud SQL IAM database authentication. For more information, seeIAM authentication.
Before you begin
- Configure the instance to use IAM database authentication. For more information, seeConfigure new instances for IAM database authentication.
- Add an IAM user,service account, or group to the database. For moreinformation, seeAdd an IAM user or service account to the databaseandAdd a group to the database.
- Add the
roles/cloudsql.instanceUser
IAM role toyour IAM user,service account, or group. It's a predefined role that containsthe necessary Cloud SQL IAMcloudsql.instances.login
permission. You need this permission to login toa database instance with IAM database authentication. For more information,seeRoles and permissions. When an IAM user is added to a database, the new database user has no privilegesto any database by default. You need touse the
GRANT
command to give the IAM database user any requiredpermissions. For more information,seeGrant database privileges to the IAM UserandGrant database privileges to a group.If you're using IAM group authentication, then the IAM user orservice account must be a member of a group that has been granted anIAM role or permissions to log in to the Cloud SQL instance.Cloud SQL creates an account after the user or service account logs into the instance for the first time.
Log in with automatic IAM database authentication
You can configure a Cloud SQL connector to automatically handleauthentication to the Cloud SQL instance on behalf of a user or anapplication. Connectors include the Cloud SQL Auth Proxy, the Go connector, the Javaconnector, and thePython connector, all of which support automatic IAM database authentication. When using aCloud SQL connector with automaticIAM database authentication, the IAM account that you use to start the connectormust be the same account that authenticates to the database.
Note: You must allow outgoing (or egress) TCPconnections to ports443
and3307
.
- Cloud SQL Connectors call APIs through the
sqladmin.googleapis.com
domain name. This domain name doesn't have a fixed IP address. Therefore, you must allow all egress TCP connections on port443
. (Port443
is the standard HTTPS port. Whenever you go to a website or make an API request, the secure connection goes through port443
of the IP address to which the website or endpoint resolves.) - While Cloud SQL Connectors can listen on any port, they create outgoing (or egress) connections to your Cloud SQL instance only on port
3307
. If your client machine has an outbound firewall policy, then make sure it allows outgoing connections to port3307
on your Cloud SQL instance's IP address. For more information, seeOptions for authenticating Cloud SQL Connectors.
To log in using automatic IAM database authentication:
Cloud SQL Auth Proxy
Important: If you use thecloud_sql_proxy
binary orthe--enable_iam_login
flag to startthe Cloud SQL Auth Proxy, then you are using v1 of the Cloud SQL Auth Proxy.Migrate to v2,cloud-sql-proxy
,and use the--auto-iam-authn
flag for IAM database authentication.For more information about migrating to v2, seeMigrating from v1 to v2.Authenticate to Google Cloud.
User
Authenticate to Google Cloud using Application Default Credentials (ADC).
Use the
gcloud auth application-default login
command. For more information, seeSet up Application Default Credentials.Service account
To authenticate to Google Cloud using ADC with a service account, youcan use service account impersonation or use a service account key.To use service account impersonation, replaceSERVICE_ACCOUNT_EMAIL_ADDRESS, and run the following command:
gcloudauthapplication-defaultlogin--impersonate-service-accountSERVICE_ACCOUNT_EMAIL_ADDRESS
For more information, seeSet up Application Default Credentials.
Start the Cloud SQL Auth Proxy with the
--auto-iam-authn
flag.Replace the following:
- INSTANCE_CONNECTION_NAME: The connection string to identify aCloud SQL instance. If you use a portother than the default PostgreSQL port, then specify the port number.For more information on how to find and construct this string, seeOptions for authenticating the Cloud SQL Auth Proxy.
./cloud-sql-proxy--auto-iam-authnINSTANCE_CONNECTION_NAME
For more information on how to start the proxy,seeStart the Cloud SQL Auth Proxy.
Warning: If you run the Cloud SQL Auth Proxy as a service, keep in mind that it requeststhe access tokens on behalf of your applications. For this reason, ensure thatonly trusted users are able to access the address and port or the Unix socketthat the Cloud SQL Auth Proxy is listening on.When you are ready to connect to the instance by using the Cloud SQL Auth Proxy,log in with the
psql
client.Replace the following:
- HOSTNAME: IP address used by the Cloud SQL Auth Proxy. By default,the Cloud SQL Auth Proxy uses the localhost address of
127.0.0.1
, but you canassign a different IP address when you start the Cloud SQL Auth Proxy. - USERNAME: For an IAM, the username is thefull email address of the user. For a service account, this is theservice account's email without the
.gserviceaccount.com
domain suffix. - PORT_NUMBER: Optional. If you specified a different portin the instance connection string, then specify that port number.
- DATABASE_NAME: The name of the database to connect to.
Run the following command:
psql-hHOSTNAME\-UUSERNAME\--portPORT_NUMBER\--dbname=DATABASE_NAME
For more information on how to connect to the Cloud SQL Auth Proxy, seeConnect with the psql client.
- HOSTNAME: IP address used by the Cloud SQL Auth Proxy. By default,the Cloud SQL Auth Proxy uses the localhost address of
Go
import("context""database/sql""fmt""log""net""os""cloud.google.com/go/cloudsqlconn""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/stdlib")funcconnectWithConnectorIAMAuthN()(*sql.DB,error){mustGetenv:=func(kstring)string{v:=os.Getenv(k)ifv==""{log.Fatalf("Warning: %s environment variable not set.",k)}returnv}// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.var(dbUser=mustGetenv("DB_IAM_USER")// e.g. 'service-account-name@project-id.iam'dbName=mustGetenv("DB_NAME")// e.g. 'my-database'instanceConnectionName=mustGetenv("INSTANCE_CONNECTION_NAME")// e.g. 'project:region:instance'usePrivate=os.Getenv("PRIVATE_IP"))// WithLazyRefresh() Option is used to perform refresh// when needed, rather than on a scheduled interval.// This is recommended for serverless environments to// avoid background refreshes from throttling CPU.d,err:=cloudsqlconn.NewDialer(context.Background(),cloudsqlconn.WithIAMAuthN(),cloudsqlconn.WithLazyRefresh(),)iferr!=nil{returnnil,fmt.Errorf("cloudsqlconn.NewDialer: %w",err)}varopts[]cloudsqlconn.DialOptionifusePrivate!=""{opts=append(opts,cloudsqlconn.WithPrivateIP())}dsn:=fmt.Sprintf("user=%s database=%s",dbUser,dbName)config,err:=pgx.ParseConfig(dsn)iferr!=nil{returnnil,err}config.DialFunc=func(ctxcontext.Context,network,instancestring)(net.Conn,error){returnd.Dial(ctx,instanceConnectionName,opts...)}dbURI:=stdlib.RegisterConnConfig(config)dbPool,err:=sql.Open("pgx",dbURI)iferr!=nil{returnnil,fmt.Errorf("sql.Open: %w",err)}returndbPool,nil}
Java JDBC
importcom.zaxxer.hikari.HikariConfig;importcom.zaxxer.hikari.HikariDataSource;importjavax.sql.DataSource;publicclassConnectorIamAuthnConnectionPoolFactoryextendsConnectionPoolFactory{// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.privatestaticfinalStringINSTANCE_CONNECTION_NAME=System.getenv("INSTANCE_CONNECTION_NAME");privatestaticfinalStringDB_IAM_USER=System.getenv("DB_IAM_USER");privatestaticfinalStringDB_NAME=System.getenv("DB_NAME");publicstaticDataSourcecreateConnectionPool(){// The configuration object specifies behaviors for the connection pool.HikariConfigconfig=newHikariConfig();// The following URL is equivalent to setting the config options below:// jdbc:postgresql:///<DB_NAME>?cloudSqlInstance=<INSTANCE_CONNECTION_NAME>&// socketFactory=com.google.cloud.sql.postgres.SocketFactory&user=<DB_IAM_USER>&// password=password// See the link below for more info on building a JDBC URL for the Cloud SQL JDBC Socket Factory// https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory#creating-the-jdbc-url// Configure which instance and what database to connect with.config.setJdbcUrl(String.format("jdbc:postgresql:///%s",DB_NAME));config.addDataSourceProperty("socketFactory","com.google.cloud.sql.postgres.SocketFactory");config.addDataSourceProperty("cloudSqlInstance",INSTANCE_CONNECTION_NAME);// If connecting using automatic database authentication, follow the instructions for// connecting using the connector, but set the DB_IAM_USER value to an IAM user or// service account that has been given access to the database.// See https://cloud.google.com/sql/docs/postgres/iam-logins for more details.config.addDataSourceProperty("enableIamAuth","true");config.addDataSourceProperty("user",DB_IAM_USER);// Password must be set to a nonempty value to bypass driver validation errors.config.addDataSourceProperty("password","password");// Explicitly set sslmode to disable to prevent driver from hanging.// The Java Connector will handle SSL so it is unneccesary to enable it at the driver level.config.addDataSourceProperty("sslmode","disable");// cloudSqlRefreshStrategy set to "lazy" is used to perform a// refresh when needed, rather than on a scheduled interval.// This is recommended for serverless environments to// avoid background refreshes from throttling CPU.config.addDataSourceProperty("cloudSqlRefreshStrategy","lazy");// ... Specify additional connection properties here.// ...// Initialize the connection pool using the configuration object.returnnewHikariDataSource(config);}}
Java R2DBC
privatestaticfinalStringCONNECTION_NAME=System.getenv("POSTGRES_CONNECTION_NAME");privatestaticfinalStringDB_NAME=System.getenv("POSTGRES_DB");privatestaticfinalStringDB_USER=System.getenv("POSTGRES_IAM_USER");privatestaticfinalStringIP_TYPE=System.getenv("IP_TYPE")==null?"PUBLIC":System.getenv("IP_TYPE");// Set up ConnectionFactoryOptionsConnectionFactoryOptionsoptions=ConnectionFactoryOptions.builder().option(DRIVER,"gcp").option(PROTOCOL,"postgresql")// Password must be set to a nonempty value to bypass driver validation errors.option(PASSWORD,"password").option(USER,DB_USER).option(DATABASE,DB_NAME).option(HOST,CONNECTION_NAME).option(IP_TYPES,IP_TYPE).option(ENABLE_IAM_AUTH,true).build();// Initialize connection poolConnectionFactoryconnectionFactory=ConnectionFactories.get(options);ConnectionPoolConfigurationconfiguration=ConnectionPoolConfiguration.builder(connectionFactory).build();this.connectionPool=newConnectionPool(configuration);
Python
importosfromgoogle.cloud.sql.connectorimportConnector,IPTypesimportpg8000importsqlalchemydefconnect_with_connector_auto_iam_authn()->sqlalchemy.engine.base.Engine:""" Initializes a connection pool for a Cloud SQL instance of Postgres. Uses the Cloud SQL Python Connector with Automatic IAM Database Authentication. """# Note: Saving credentials in environment variables is convenient, but not# secure - consider a more secure solution such as# Cloud Secret Manager (https://cloud.google.com/secret-manager) to help# keep secrets safe.instance_connection_name=os.environ["INSTANCE_CONNECTION_NAME"]# e.g. 'project:region:instance'db_iam_user=os.environ["DB_IAM_USER"]# e.g. 'sa-name@project-id.iam'db_name=os.environ["DB_NAME"]# e.g. 'my-database'ip_type=IPTypes.PRIVATEifos.environ.get("PRIVATE_IP")elseIPTypes.PUBLIC# initialize Cloud SQL Python Connector objectconnector=Connector(refresh_strategy="LAZY")defgetconn()->pg8000.dbapi.Connection:conn:pg8000.dbapi.Connection=connector.connect(instance_connection_name,"pg8000",user=db_iam_user,db=db_name,enable_iam_auth=True,ip_type=ip_type,)returnconn# The Cloud SQL Python Connector can be used with SQLAlchemy# using the 'creator' argument to 'create_engine'pool=sqlalchemy.create_engine("postgresql+pg8000://",creator=getconn,# ...)returnpool
Log in with manual IAM database authentication
Note: If you plan to use the Cloud SQL Auth Proxy, the Go connector, the Java connector, or thePython connector, then seeLog in with automatic IAM database authentication.A user or an application can authenticate to the database using IAMby manually requesting an access token from Google Cloud and presenting it tothe database. Using thegcloud CLI, you can explicitly request anOAuth 2.0 token with theCloud SQL Admin API scope that is used to log in to the database. When you log in as adatabase user with manual IAM database authentication, you use your email address as the username andthe access token as the password. You can use this method with either a directconnection to the database or with a Cloud SQL connector.
In this procedure, you authenticate to Google Cloud, request an access token,and then connect to the database by passing in the token as the password forthe IAM database user. Use these steps to connect withouttheCloud SQL Auth Proxy.
For these steps, you must:
gcloud sql generate-login-token
command to generate your authentication token.To log in using manual IAM database authentication:
gcloud
Authenticate to Google Cloud.
User
Authenticate to IAM using
gcloud auth login
. For moreinformation, seeAuthorize with a user account.Service account
Authenticate to IAM using
gcloud auth activate-service-account
.For more information, seeAuthorize with a service account.Request the access token, and log in with a client.
Warning: You can use your OAuth 2.0 token tomake authenticated requests on your behalf. Make sure to keep it secure,and be careful where you store it.Replace the following:
- HOSTNAME: The IP address of the instance, either the publicIP address or private IP address.
- USERNAME: For an IAM, the username is thefull email address of the user. For a service account, this is theservice account's email without the
.gserviceaccount.com
domain suffix. - DATABASE_NAME: The name of the database to connect to.
PGPASSWORD=`gcloudsqlgenerate-login-token`\psql"sslmode=require \ hostaddr=HOSTNAME \ user=USERNAME \ dbname=DATABASE_NAME"\--no-password
If
Note: The OAuth 2.0 token can't be entered or pasted directly into a password field, because that token is longer than the field's maximum size. Use an environment variable to pass the authentication token to the command. The provided command is for Unix/Linux environments. If you use Microsoft Windows, substitute Windows environment variable settings.ssl_mode
on your Cloud SQL instance is configured toTRUSTED_CLIENT_CERTIFICATE_REQUIRED
, then we recommend that youlog in with automatic IAM database authenticationto enforce client identity validation.
What's next
- Learn more aboutIAM database authentication.
- Learn how toenable and view login information in audit logs.
- Learn how tocreate users and service accounts that use Cloud SQL IAM database authentication.
- Learn how tomanage users and service accounts for IAM database authentication.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-07-16 UTC.