Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Nesta página, explicamos o processo de fazer login em uma instância do AlloyDB para PostgreSQL usando
uma conta preparada com Identity and Access Management (IAM). Ele ilustra o processo mostrando como fazer login com base no IAM usando o cliente de linha de comando psql.
Para uma visão geral da conexão com instâncias do AlloyDB, consulte
Visão geral da conexão.
Antes de começar
Seu projeto, cluster, instâncias e contas de usuário do IAM precisam de preparação antes que você possa fazer login em uma instância do AlloyDB usando credenciais do IAM.
Um usuário ou aplicativo pode se autenticar em um banco de dados do AlloyDB
seguindo estas etapas:
Se ainda não tiver feito isso, autorize a
Google Cloud CLI usando o
mesmo usuário ou conta de serviço que você quer usar para fazer login na sua
instância do AlloyDB.
O token OAuth 2.0 permite que você ou qualquer pessoa faça solicitações autenticadas para
Google Cloud em seu nome. Trate o token com o mesmo nível de segurança de uma senha. Armazene o token com segurança ou evite armazená-lo. O exemplo de uso de psql mais adiante nesta página
demonstra uma maneira de solicitar, usar e descartar um token do OAuth 2.0 em uma
única ação.
Faça login em uma instância do AlloyDB com técnicas padrão do PostgreSQL usando estas credenciais:
Apresente o token de acesso adquirido na etapa anterior como sua
senha.
Para uma conta de usuário do IAM, o nome de usuário do banco de dados é o
endereço de e-mail completo da conta.
Para uma conta de serviço do IAM, o nome de usuário do banco de dados é o
endereço de e-mail da conta sem o sufixo .gserviceaccount.com.
O comando psql a seguir demonstra uma maneira de fazer login como um
usuário do IAM na linha de comando. Ele atribui a saída de gcloud
auth print-access-token à variável de ambiente PGPASSWORD, que psql
usa posteriormente como uma senha de login do banco de dados.
INSTANCE_ADDRESS: o endereço IP da instância do AlloyDB a que você quer se conectar.
USERNAME: um identificador para o usuário do IAM
autenticar com a instância.
Para uma conta de usuário do IAM, forneça o endereço de e-mail completo da conta. Por exemplo, kai@altostrat.com
Para uma conta de serviço do IAM, forneça o endereço da conta sem o sufixo .gserviceaccount.com. Por exemplo, para especificar
a conta de serviço my-service@my-project.iam.gserviceaccount.com, use o valor my-service@my-project.iam aqui.
DATABASE: o nome do banco de dados a ser conectado.
O psql trunca senhas inseridas na linha de comando que tenham mais de 100 caracteres. Para usar psql com um token OAuth 2.0 como senha de login,
defina a variável de ambiente PGPASSWORD conforme demonstrado neste
exemplo, em vez de colar manualmente quando solicitado.
A conta do IAM usada para executar o
cliente proxy ou os Language Connectors precisa ser a mesma
conta adicionada como usuário do banco de dados. Por exemplo, se você executar sua carga de trabalho
usando a conta de usuário do IAM kai@altostrat.com, poderá usar
o cliente proxy ou os conectores de linguagem para
autenticar automaticamente o usuário do banco de dados kai@altostrat.com sem
especificar um token OAuth 2.0. Neste exemplo, a autenticação automática não funciona com nenhum outro usuário do banco de dados, exceto kai@altostrat.com.
Proxy de autenticação
Para usar o proxy de autenticação, é necessário executar o cliente do proxy de autenticação do AlloyDB com a flag
--auto-iam-authn ativada.
Para usar os conectores de linguagem, é necessário ativar a autenticação do IAM de forma programática. Há uma opção correspondente para cada idioma em Configurar os conectores de linguagem do AlloyDB.
Resolver problemas de autenticação do IAM
Para determinar a causa de uma tentativa de autenticação baseada no IAM com falha, siga estas etapas:
No console Google Cloud , acesse a página "Explorador de registros":
Em Tipo de recurso, clique em Instância do AlloyDB.
Em Gravidade, clique em Alerta.
Se Alerta não for uma opção, não haverá falhas de autenticação registradas no período selecionado. Talvez seja necessário ajustar a janela usando os controles do Explorador de registros.
Em Resultados da consulta, verifique as entradas de registro de uma das seguintes mensagens:
Request had invalid authentication credentials.
O token de acesso é inválido.
Caller does not have required permission to use project.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-25 UTC."],[[["\u003cp\u003eThis guide outlines how to log in to an AlloyDB for PostgreSQL instance using Identity and Access Management (IAM) credentials, primarily through the \u003ccode\u003epsql\u003c/code\u003e command-line client.\u003c/p\u003e\n"],["\u003cp\u003eAuthentication with an OAuth 2.0 token requires authorizing the Google Cloud CLI and obtaining a token, which is then used as the password for database access, with the username being the IAM user's email address or the service account's email without the suffix.\u003c/p\u003e\n"],["\u003cp\u003eThe document details how to authenticate using the \u003ccode\u003epsql\u003c/code\u003e command by assigning the OAuth token to the \u003ccode\u003ePGPASSWORD\u003c/code\u003e environment variable, ensuring correct syntax for IAM user or service accounts.\u003c/p\u003e\n"],["\u003cp\u003eAlloyDB Auth Proxy and Language Connectors can be used to automate IAM authentication, eliminating the need to manually provide an OAuth 2.0 token, but requiring the use of the same IAM account for the workload and database user.\u003c/p\u003e\n"],["\u003cp\u003eTroubleshooting steps are provided to resolve IAM authentication failures, including checking logs for specific error messages and verifying access token validity, permissions, principal matching, and required scopes.\u003c/p\u003e\n"]]],[],null,["# Connect using an IAM account\n\nThis page explains the process of logging into an AlloyDB for PostgreSQL instance using\nan account prepared with Identity and Access Management (IAM). It illustrates the process\nby showing how to perform an IAM-based login using the `psql`\ncommand-line client.\n\nFor an overview of connecting to AlloyDB instances, see\n[Connection overview](/alloydb/docs/connection-overview).\n\nBefore you begin\n----------------\n\nYour project, cluster, instances, and IAM user accounts all\nrequire preparation before you can log in to an AlloyDB instance\nusing IAM credentials.\n\nFor more information, see [Manage IAM\nauthentication](/alloydb/docs/manage-iam-authn).\n\nAuthenticate with an OAuth 2.0 token\n------------------------------------\n\nA user or an application can authenticate with an AlloyDB database\nby following these steps:\n\n1. If you haven't already done so, [authorize the\n Google Cloud CLI](https://cloud.google.com/sdk/docs/authorizing) using the\n same user or service account that you want to log in to your\n AlloyDB instance with.\n\n2. Request an OAuth 2.0 token from Google Cloud using [the\n `gcloud auth print-access-token`\n command](/sdk/gcloud/reference/auth/print-access-token):\n\n gcloud auth print-access-token\n\n The Google Cloud prints an OAuth 2.0 token as the output of this\n command.\n\n For additional security, you can restrict the token for use with only\n AlloyDB authentication by following these alternative steps:\n 1. Add the\n `alloydb.login` scope to your current environment's access credentials using [the\n `gcloud auth application-default login`\n command](/sdk/gcloud/reference/auth/application-default/login), if you have not already done so:\n\n gcloud auth application-default login --scopes=https://www.googleapis.com/auth/alloydb.login,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email,openid\n\n 2. Print a restricted OAuth 2.0 token using [the `gcloud auth application-default print-access-token`\n command](/sdk/gcloud/reference/auth/application-default/print-access-token),\n scoping the token only to AlloyDB authentication:\n\n gcloud auth application-default print-access-token ---scopes=https://www.googleapis.com/auth/alloydb.login\n\n | **Caution:** Treat your OAuth 2.0 token as sensitive information. Either store it securely, or don't store it at all after use.\n\n The OAuth 2.0 token lets you---or anyone---make authenticated requests to\n Google Cloud on your behalf. Treat the token with the same level\n of security as a password. Either store the token securely, or avoid\n storing it at all. The example use of `psql` later on this page\n demonstrates a way to request, use, and discard an OAuth 2.0 token in a\n single action.\n3. Log in to an AlloyDB instance with standard PostgreSQL\n techniques, using these credentials:\n\n - Present the access token you acquired in the previous step as your\n password.\n\n - For an IAM user account, the database username is the\n account's full email address.\n\n - For an IAM service account, the database username is the\n account's email address without the `.gserviceaccount.com` suffix.\n\nThe following `psql` command demonstrates one way to log in to an\nIAM user on the command line. It assigns the output of `gcloud\nauth print-access-token` to the `PGPASSWORD` environment variable, which `psql`\nsubsequently uses as a database login password. \n\n PGPASSWORD=$(gcloud auth print-access-token) psql \\\n -h \u003cvar translate=\"no\"\u003eINSTANCE_ADDRESS\u003c/var\u003e \\\n -U \u003cvar translate=\"no\"\u003eUSERNAME\u003c/var\u003e \\\n -d \u003cvar translate=\"no\"\u003eDATABASE\u003c/var\u003e\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003eINSTANCE_ADDRESS\u003c/var\u003e: The IP address of the\n AlloyDB instance to connect to.\n\n- \u003cvar translate=\"no\"\u003eUSERNAME\u003c/var\u003e: An identifier for the IAM user\n to authenticate with the instance.\n\n For an IAM user account, supply the user account's full email\n address. For example, `kai@altostrat.com`.\n\n For an IAM service account, supply the service account's\n address *without* the `.gserviceaccount.com` suffix. For example, to specify\n the service account `my-service@my-project.iam.gserviceaccount.com`, you\n would use the value `my-service@my-project.iam` here.\n- \u003cvar translate=\"no\"\u003eDATABASE\u003c/var\u003e: The name of the database to connect to.\n\nNote that `psql` truncates passwords entered on the command line that are longer\nthan 100 characters. To use `psql` with an OAuth 2.0 token as a login password,\nyou must set the `PGPASSWORD` environment variable as demonstrated in this\nexample, rather than manually paste it when prompted.\n\nAuthenticate automatically\n--------------------------\n\nTo automatically authenticate an IAM-based AlloyDB\nuser without the need for an OAuth 2.0 token, you have two options:\n[AlloyDB Auth Proxy](/alloydb/docs/auth-proxy/connect) and\n[AlloyDB Language Connectors](/alloydb/docs/connect-language-connectors).\n\nThe IAM account that you use to run the\nproxy client or Language Connectors must be the same\naccount that you added as a database user. For example, if you run your workload\nusing the IAM user account `kai@altostrat.com`, then you can use\nthe proxy client or Language Connectors to\nautomatically authenticate the `kai@altostrat.com` database user without\nspecifying an OAuth 2.0 token. In this example, automatic authentication does\nnot work with any other database user except for `kai@altostrat.com`. \n\n### Auth Proxy\n\nUsing Auth Proxy requires running the AlloyDB Auth Proxy client with the\n`--auto-iam-authn` flag enabled.\n\nFor more information about running the Auth Proxy, see\n[Connect using the AlloyDB Auth Proxy](/alloydb/docs/auth-proxy/connect).\n\n### Language Connectors\n\nUsing Language Connectors requires enabling IAM\nauthentication programmatically. There is a corresponding option for each\nlanguage on\n[Configure the AlloyDB Language Connectors](/alloydb/docs/connect-language-connectors#configure-connectors).\n\nTroubleshoot IAM authentication\n-------------------------------\n\nTo determine the cause of a failed IAM-based authentication\nattempt, follow these steps:\n\n1. In the Google Cloud console, go to the Logs Explorer page:\n\n [Go to Logs Explorer](https://console.cloud.google.com/logs/query)\n2. Under **Resource type** , click **AlloyDB instance**.\n\n3. Under **Severity** , click **Alert**.\n\n If **Alert** is not an option, then there are no authentication failures logged within the\n selected time window. You may need to adjust the window using the\n Logs Explorer controls.\n4. Under **Query results**, check the log entries for one of the following messages:\n\n `Request had invalid authentication credentials.`\n : The access token is invalid.\n\n `Caller does not have required permission to use project.`\n : The IAM principal doesn't have [the necessary IAM roles](/alloydb/docs/manage-iam-authn#role) or permissions.\n The full error message specifies the missing roles or permissions.\n\n `IAM principal does not match database user.`\n\n : The authenticated IAM principal specified by the access token doesn't match the database user that you want to connect as.\n\n To view the principal specified by the token, run the following command: \n\n ```\n curl -H \"Content-Type: application/x-www-form-urlencoded\" -d \"access_token=ACCESS_TOKEN\" https://www.googleapis.com/oauth2/v1/tokeninfo\n ```\n\n Replace \u003cvar translate=\"no\"\u003eACCESS_TOKEN\u003c/var\u003e with the OAuth 2.0 access token.\n\n `Request had insufficient scopes.`\n : The access token does not contain either the `alloydb.login` scope or the `cloud-platform` scope. At least one of these scopes is required.\n\nWhat's next\n-----------\n\n- [Manage your IAM authentication](/alloydb/docs/database-users/manage-iam-auth)"]]