Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Como registrar números de telefone de teste
Neste documento, mostramos como registrar números de telefone no Identity Platform
para fins de desenvolvimento. Isso permite testar métodos de autenticação que
envolvem o envio de uma mensagem SMS, como login por telefone e autenticação
multifator.
Usar um número de teste (em vez de um número real seu) tem várias vantagens:
Ele se integra perfeitamente aos emuladores de iOS e Android.
Ele elimina a sobrecarga de enviar um SMS real.
É possível executar testes consecutivos com o mesmo número de telefone sem ser
limitado.
Você pode gravar testes de integração sem ser bloqueado por verificações de segurança.
Ele não consome sua cota de uso.
Você pode registrar até 10 números de telefone para desenvolvimento.
Se você estiver testando a autenticação por telefone, localize-a na lista de provedores
e clique no ícone Editar. Se você estiver testando a autenticação multifator,
selecione a guia SMS multifator e clique em Editar.
Em Números de telefone para testes, insira um número de telefone e um código
de verificação para se inscrever.
O número de telefone precisa usar o
formato E.164 e ainda não pode ser atribuído a um usuário do Identity
Platform atual. O código de verificação precisa ter seis dígitos.
Por motivos de segurança, escolha números difíceis de adivinhar e evite
padrões óbvios como +1 123-456-7890.
Clique em Salvar.
Os números de telefone de teste são tratados como números de telefone reais pelo
Identity Platform. Portanto, armazene-os com segurança e gire-os em intervalos
regulares.
Teste manual
Você pode começar a usar imediatamente números de telefone de teste no seu app, diretamente
ou usando os emuladores iOS e Android. Ao fazer login com um número de telefone de teste,
nenhum código de verificação SMS é enviado. Insira o código registrado
durante a criação do número de teste.
Depois de fazer login, um usuário do Identity Platform é criado usando o número de telefone
de teste. Esse usuário tem o mesmo comportamento e propriedades de um usuário real,
incluindo um token de ID válido, o que significa que ele pode acessar todos os seus aplicativos e serviços.
Para restringir o acesso dos usuários de teste, crie um papel de teste com
permissões limitadas e atribua-o usando
declarações personalizadas.
Teste de integração
Além do teste manual, o SDK do cliente contém APIs que podem ajudar
a escrever testes de integração. Essas APIs desativam os requisitos de verificação do reCAPTCHA
e do app, o que facilita a omissão com a automação.
O exemplo a seguir mostra como testar o login de um usuário com um número de telefone:
JavaScript
// Turn off phone app verification.firebase.auth().settings.appVerificationDisabledForTesting=true;varphoneNumber="+16505554567";vartestVerificationCode="123456";// Render a fake reCAPTCHA and resolve without app verification.varappVerifier=newfirebase.auth.RecaptchaVerifier('recaptcha-container');// signInWithPhoneNumber will call appVerifier.verify(), which will resolve// with a fake reCAPTCHA response.firebase.auth().signInWithPhoneNumber(phoneNumber,appVerifier).then(function(confirmationResult){// confirmationResult can resolve using testVerificationCode.returnconfirmationResult.confirm(testVerificationCode)}).catch(function(error){// Error; SMS not sent// ...});
Os verificadores do reCAPTCHA simulados visíveis e invisíveis se comportam de maneira diferente quando
a verificação do app está desativada:
reCAPTCHA visível: para simular um clique do usuário, o reCAPTCHA se resolve
automaticamente após um breve atraso.
reCAPTCHA invisível: para simular a verificação de apps, o reCAPTCHA será
resolvido automaticamente quando appVerifier.verify() for chamado.
Os reCAPTCHA externos ainda acionam os callbacks quando eles são resolvidos ou expiram.
A seguir
Adicione a autenticação multifator ao seu
app da Web,
iOS ou
Android.
[[["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-11 UTC."],[[["\u003cp\u003eThis guide details how to register up to 10 test phone numbers with Identity Platform for development and testing, allowing you to simulate phone-based authentication methods.\u003c/p\u003e\n"],["\u003cp\u003eUsing test numbers eliminates the need for real SMS messages, prevents throttling, bypasses security checks, and doesn't affect your usage quota.\u003c/p\u003e\n"],["\u003cp\u003eTo register, navigate to the Identity Providers page in the Google Cloud console, input a phone number in E.164 format and a six-digit verification code under "Phone numbers for testing," ensuring the number isn't already in use by an existing Identity Platform user.\u003c/p\u003e\n"],["\u003cp\u003eTest phone numbers function like real numbers within Identity Platform, allowing you to use them directly or with iOS/Android emulators and requiring the registered verification code for sign-in.\u003c/p\u003e\n"],["\u003cp\u003eClient SDK APIs are available to simplify integration testing by disabling reCAPTCHA and app verification, demonstrated with a JavaScript example that also showcases mock reCAPTCHA behavior.\u003c/p\u003e\n"]]],[],null,["# Registering test phone numbers\n==============================\n\nThis document shows you how to register phone numbers with Identity Platform\nfor development purposes. This allows you to test authentication methods that\ninvolve sending an SMS message, such as phone sign-in and multi-factor\nauthentication.\n\nUsing a test number (rather than a real number you own) has several benefits:\n\n- It integrates seamlessly with the iOS and Android emulators.\n- It eliminates the overhead of sending an actual SMS.\n- You can execute consecutive tests with the same phone number without being throttled.\n- You can write integration tests without being blocked by security checks.\n- It doesn't consume your usage quota.\n\nYou can register up to 10 phone numbers for development.\n\nRegistering a test phone number\n-------------------------------\n\nTo register a test phone number:\n\n1. Go to the **Identity Providers** page in the Google Cloud console. \n\n [Go to the Identity Providers page](https://console.cloud.google.com/customer-identity/providers) \n\n2. If you are testing phone authentication, locate it in the list of providers,\n then click the **Edit** icon. If you are testing multi-factor\n authentication, select the **Multi-factor SMS** tab, then click **Edit**.\n\n3. Under **Phone numbers for testing**, enter a phone number and verification\n code to register.\n\n The phone number should use\n [E.164 format](https://wikipedia.org/wiki/E.164), and cannot already be assigned to an existing\n Identity Platform user. The verification code should be six digits.\n For security purposes, choose numbers that are difficult to guess, and avoid\n obvious patterns like `+1 123-456-7890`.\n4. Click **Save**.\n\nTesting phone numbers are treated like real phone numbers by\nIdentity Platform, so store them securely and rotate them at regular\nintervals.\n\nManual testing\n--------------\n\nYou can immediately begin using test phone numbers in your app, either directly\nor using the iOS and Android emulators. When signing in with a test phone\nnumber, no SMS verification code is sent; instead, enter the code you registered\nwhen creating the test number.\n\nAfter signing in, an Identity Platform user is created using the test phone\nnumber. This user has the same behavior and properties as a real user,\nincluding a valid ID token, meaning it can access all your apps and services.\n\nTo restrict access from your test users, consider creating a test role with\nlimited permissions and assigning it using\n[custom claims](/identity-platform/docs/how-to-configure-custom-claims).\n\nIntegration testing\n-------------------\n\nIn addition to manual testing, the client SDK contains APIs that can help\nwrite integration tests. These APIs disable the reCAPTCHA and app verification\nrequirements, making them easier bypass with automation.\n\nThe following example shows how to test signing in a user with a phone number: \n\n### JavaScript\n\n // Turn off phone app verification.\n firebase.auth().settings.appVerificationDisabledForTesting = true;\n\n var phoneNumber = \"+16505554567\";\n var testVerificationCode = \"123456\";\n\n // Render a fake reCAPTCHA and resolve without app verification.\n var appVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\n // signInWithPhoneNumber will call appVerifier.verify(), which will resolve\n // with a fake reCAPTCHA response.\n firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)\n .then(function (confirmationResult) {\n // confirmationResult can resolve using testVerificationCode.\n return confirmationResult.confirm(testVerificationCode)\n }).catch(function (error) {\n // Error; SMS not sent\n // ...\n });\n\nVisible and invisible mock reCAPTCHA verifiers behave differently when\napp verification is disabled:\n\n- **Visible reCAPTCHA:** To simulate a user click, the reCAPTCHA will resolve\n itself automatically after a brief delay.\n\n- **Invisible reCAPTCHA** : To simulate app verification, the reCAPTCHA will\n resolve automatically when `appVerifier.verify()` is called.\n\nMock reCAPTCHAs will still trigger their callbacks when they resolve or expire.\n\nWhat's next\n-----------\n\n- Add multi-factor authentication to your [web](/identity-platform/docs/web/mfa), [iOS](/identity-platform/docs/ios/mfa), or [Android](/identity-platform/docs/android/mfa) app."]]