Logging in to a database with IAM database authentication

This page describes how users and service accounts can log in to Cloud SQL databases using Cloud SQL IAM database authentication. For more information, see Overview of Cloud SQL IAM database authentication.

Before you begin

Logging in with manual IAM database authentication

A user or an application can authenticate to the database using IAM by manually requesting an access token from Google Cloud and presenting it to the database. Using the Cloud SDK, you can explicitly request an OAuth 2.0 token with the Cloud SQL API scope that is used to log in to the database. When you log in as a database user with manual IAM database authentication, you use your email address as the username and the access token as the password. You can use this method with either a direct connection to the database or with a Cloud SQL connector.

In these steps, you authenticate to Google Cloud, request an access token, and then connect to the database by passing in the token as the password for the IAM database user.

For these steps, you must:

To use the Cloud SDK to generate this token and log in:

gcloud

  1. Authenticate to Google Cloud.

    User

    Authenticate to IAM using gcloud auth login. For more information, see Authorizing with a user account.

    Service account

    Authenticate to IAM using gcloud auth activate-service-account. For more information, see Authorizing with a service account.

  2. Request the access token and log in with a client.

    Replace the following:

    • HOSTNAME: The IP address of the instance.
    • USERNAME: For an IAM user account, this is the user's email address, without the @ or domain name. For example, for test-user@gmail.com, enter test-user. For a service account, this is the service account's email address without the @project-id.iam.gserviceaccount.com suffix.

    MYSQL_PWD=`gcloud auth print-access-token` mysql --enable-cleartext-plugin 
    --ssl-ca=server-ca.pem --ssl-cert=client-cert.pem
    --ssl-key=client-key.pem --host=HOSTNAME
    --user=USERNAME

    What's next