Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Como gerenciar usuários de vários fatores programaticamente
Neste documento, mostramos como usar o SDK Admin do Identity Platform para gerenciar
usuários de vários fatores programaticamente. Ao gerenciar usuários de vários fatores
você tem acesso a um intervalo maior de propriedades em comparação
com usuários de fator único.
É possível recuperar dados relacionados aos vários fatores do usuário, como uma lista de
segundos fatores registrados, a partir do objeto UserRecord. Para conseguir um registro de usuário, chame
getUser() ou getUserByEmail().
O exemplo abaixo mostra um usuário inscrito com vários fatores:
// console.log(userRecord.toJSON());{uid:'some-uid',displayName:'John Doe',email:'johndoe@gmail.com',photoURL:'http://www.example.com/12345678/photo.png',emailVerified:true,phoneNumber:'+11234567890',// Set this user as admin.customClaims:{admin:true},// User with Google provider.providerData:[{uid:'google-uid',email:'johndoe@gmail.com',displayName:'John Doe',photoURL:'http://www.example.com/12345678/photo.png',providerId:'google.com'}],multiFactor:{enrolledFactors:[// 2FA with SMS as 2nd factor.{uid:'53HG4HG45HG8G04GJ40J4G3J',phoneNumber:'+16505551234',displayName:'Work phone',enrollmentTime:'Fri, 22 Sep 2017 01:49:58 GMT',factorId:'phone',},],},};
Listar usuários
O código abaixo mostra como listar todos os usuários e verificar se eles têm um fator secundário
inscrito:
Os usuários são retornados em lotes, ordenados pelo uid. Cada lote de resultados
contém uma lista de usuários e um token de próxima página usado para buscar o próximo lote.
Quando todos os usuários tiverem sido listados, nenhum pageToken será retornado.
O campo maxResult especifica o tamanho máximo do lote. O valor padrão e
valor máximo é 1.000.
Criar um usuário
Chame createUser() para criar um novo usuário. Os novos usuários com fatores secundários precisam
ter um endereço de e-mail verificado (definir emailVerified como true) e usar um
primeiro fator compatível para fazer login. Até cinco fatores secundários são permitidos por
usuário.
O exemplo mostra como criar um novo usuário com dois fatores secundários:
admin.auth().createUser({uid:'123456789',email:'user@example.com',emailVerified:true,password:'password',multiFactor:{enrolledFactors:[// When creating users with phone second factors, the uid and// enrollmentTime should not be specified. These will be provisioned by// the Auth server.// Primary second factor.{phoneNumber:'+16505550001',displayName:'Corpphone',factorId:'phone',},// Backup second factor.{phoneNumber:'+16505550002',displayName:'Personalphone',factorId:'phone'},],},}).then((userRecord)=>{console.log(userRecord.multiFactor.enrolledFactors);}).catch((error)=>{console.log(error);});
Como atualizar um usuário
Para atualizar um usuário, chame updateUser():
admin.auth().updateUser(uid:'123456789',{multiFactor:{enrolledFactors:[{// uid will be auto-generated.phoneNumber:'+16505550003',displayName:'Spouse\'sphone',factorId:'phone',},{// uid can also be specified. This is useful if a new second factor is added and an// existing enrolled second factor is kept unmodified.uid:'existing-enrolled-mfa-uid',phoneNumber:'+16505550004',displayName:'Personalphone',factorId:'phone',},{phoneNumber:'+16505550005',displayName:'Backupphone',factorId:'phone',// Enrollment time can also be explicitly specified.enrollmentTime:newDate().toUTCString(),},],},}).then((userRecord)=>{console.log(userRecord.multiFactor.enrolledFactors);}).catch((error)=>{console.log(error);});
Como adicionar um novo fator secundário
Chamar updateUser() com uma lista de enrolledFactors apagará todos os fatores secundários
atuais do usuário. Para adicionar um novo fator secundário ao preservar
os atuais, procure o usuário primeiro e, em seguida, adicione o novo fator à
lista:
[[["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 document provides guidance on managing multi-factor authentication (MFA) users programmatically using the Identity Platform Admin SDK, specifically with Node.js.\u003c/p\u003e\n"],["\u003cp\u003eYou can retrieve a user's MFA data, such as their enrolled second factors, using the \u003ccode\u003egetUser()\u003c/code\u003e or \u003ccode\u003egetUserByEmail()\u003c/code\u003e methods, which returns a \u003ccode\u003eUserRecord\u003c/code\u003e object with MFA details.\u003c/p\u003e\n"],["\u003cp\u003eThe document explains how to list users and check if they have any secondary factors enrolled via \u003ccode\u003eadmin.auth().listUsers()\u003c/code\u003e, as well as how to manage batches of user data using the \u003ccode\u003epageToken\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eCreating new users with secondary factors involves using \u003ccode\u003ecreateUser()\u003c/code\u003e, ensuring the email is verified and up to five secondary factors are set up.\u003c/p\u003e\n"],["\u003cp\u003eModifying existing user MFA settings is done through \u003ccode\u003eupdateUser()\u003c/code\u003e, allowing the addition or removal of secondary factors, and managing their attributes.\u003c/p\u003e\n"]]],[],null,["# Managing multi-factor users programmatically\n============================================\n\nThis document shows you how to use the Identity Platform Admin SDK to manage\nyour multi-factor users programmatically. When managing multi-factor users,\nyou have access to an increased range of user properties compared\nto [single-factor users](/identity-platform/docs/admin/manage-users).\n\nBefore you begin\n----------------\n\n- [Install the Node.js Admin SDK](/identity-platform/docs/install-admin-sdk). Other Admin SDK languages are not currently supported.\n\nGetting users\n-------------\n\nYou can retrieve user multi-factor related data, such as a list of enrolled\nsecond factors, from the `UserRecord` object. To get a user record, call\n`getUser()` or `getUserByEmail()`.\n\nThe example below shows a multi-factor enrolled user: \n\n // console.log(userRecord.toJSON());\n {\n uid: 'some-uid',\n displayName: 'John Doe',\n email: 'johndoe@gmail.com',\n photoURL: 'http://www.example.com/12345678/photo.png',\n emailVerified: true,\n phoneNumber: '+11234567890',\n // Set this user as admin.\n customClaims: {admin: true},\n // User with Google provider.\n providerData: [{\n uid: 'google-uid',\n email: 'johndoe@gmail.com',\n displayName: 'John Doe',\n photoURL: 'http://www.example.com/12345678/photo.png',\n providerId: 'google.com'\n }],\n multiFactor: {\n enrolledFactors: [\n // 2FA with SMS as 2nd factor.\n {\n uid: '53HG4HG45HG8G04GJ40J4G3J',\n phoneNumber: '+16505551234',\n displayName: 'Work phone',\n enrollmentTime: 'Fri, 22 Sep 2017 01:49:58 GMT',\n factorId: 'phone',\n },\n ],\n },\n };\n\nListing users\n-------------\n\nThe code below shows how to list all users and check if they have a secondary\nfactor enrolled: \n\n admin.auth().listUsers(1000, nextPageToken)\n .then((listUsersResult) =\u003e {\n listUsersResult.users.forEach((userRecord) =\u003e {\n // Multi-factor enrolled users second factors can be retrieved via:\n if (userRecord.multiFactor) {\n userRecord.multiFactor.enrolledFactors.forEach((enrolledFactor) =\u003e {\n console.log(userRecord.uid, enrolledFactor.toJSON());\n });\n }\n });\n })\n .catch((error) =\u003e {\n console.log('Error listing users:', error);\n });\n\nUsers are returned in batches, ordered by their `uid`. Each batch of results\ncontains a list of users, and a next page token used to fetch the next batch.\nWhen all users have been listed, no `pageToken` is returned.\n\nThe `maxResult` field specifies the maximum batch size. The default and\nmaximum value is 1000.\n\nCreating a user\n---------------\n\nCall `createUser()` to create a new user. New users with secondary factors must\nhave a verified email address (set `emailVerified` to `true`) and use a\nsupported first factor to sign in. Up to 5 secondary factors are allowed per\nuser.\n\nThe example shows how to create a new user with 2 secondary factors: \n\n admin.auth().createUser({\n uid: '123456789',\n email: 'user@example.com',\n emailVerified: true,\n password: 'password',\n multiFactor: {\n enrolledFactors: [\n // When creating users with phone second factors, the uid and\n // enrollmentTime should not be specified. These will be provisioned by\n // the Auth server.\n // Primary second factor.\n {\n phoneNumber: '+16505550001',\n displayName: 'Corp phone',\n factorId: 'phone',\n },\n // Backup second factor.\n {\n phoneNumber: '+16505550002',\n displayName: 'Personal phone',\n factorId: 'phone'\n },\n ],\n },\n })\n .then((userRecord) =\u003e {\n console.log(userRecord.multiFactor.enrolledFactors);\n })\n .catch((error) =\u003e {\n console.log(error);\n });\n\nUpdating a user\n---------------\n\nTo update an existing user, call `updateUser()`: \n\n admin.auth().updateUser(uid: '123456789', {\n multiFactor: {\n enrolledFactors: [\n {\n // uid will be auto-generated.\n phoneNumber: '+16505550003',\n displayName: 'Spouse\\'s phone',\n factorId: 'phone',\n },\n {\n // uid can also be specified. This is useful if a new second factor is added and an\n // existing enrolled second factor is kept unmodified.\n uid: 'existing-enrolled-mfa-uid',\n phoneNumber: '+16505550004',\n displayName: 'Personal phone',\n factorId: 'phone',\n },\n {\n phoneNumber: '+16505550005',\n displayName: 'Backup phone',\n factorId: 'phone',\n // Enrollment time can also be explicitly specified.\n enrollmentTime: new Date().toUTCString(),\n },\n ],\n },\n })\n .then((userRecord) =\u003e {\n console.log(userRecord.multiFactor.enrolledFactors);\n })\n .catch((error) =\u003e {\n console.log(error);\n });\n\n### Adding a new secondary factor\n\nCalling `updateUser()` with a list of `enrolledFactors` will erase any of the\nuser's current secondary factors. To add a new secondary factor while\npreserving the existing ones, look up the user first, then add the new factor to\nthe list: \n\n function enrollSecondFactor(userId, secondFactorPhoneNumber, secondFactorDisplayName) {\n return admin.auth().getUser(userId)\n .then((userRecord) =\u003e {\n const updatedList = (userRecord.multiFactor &&\n userRecord.multiFactor.toJSON().enrolledFactors) || [];\n updatedList.push({\n phoneNumber: secondFactorPhoneNumber,\n displayName: secondFactorDisplayName,\n factorId: 'phone',\n });\n return admin.auth().updateUser(userRecord.uid, {\n multiFactor: {\n enrolledFactors: updatedList,\n },\n });\n })\n .catch((error) =\u003e {\n console.log(error);\n });\n }\n\n### Removing a secondary factor\n\nTo completely unenroll a user from multi-factor authentication, set\n`enrolledFactors` to `null` or an empty array: \n\n admin.auth().updateUser(uid: '123456789', {\n multiFactor: {\n enrolledFactors: null,\n },\n })\n .then((userRecord) =\u003e {\n console.log(userRecord.multiFactor);\n })\n .catch((error) =\u003e {\n console.log(error);\n });\n\nWhat's next\n-----------\n\n- [Migrate users from an existing app to Identity Platform](/identity-platform/docs/migrating-users)"]]