Firebase kicks out current user

So I have this issue where every time I add a new user account, it kicks out the current user that is already signed in. I read the firebase api and it said that "If the new account was created, the user is signed in automatically" But they never said anything else about avoiding that.

      addEmployees: function(formData){
        firebase.auth().createUserWithEmailAndPassword(, formData.password).then(function(data){

I'm the admin and I'm adding accounts into my site. I would like it if I can add an account without being signed out and signed into the new account. Any way i can avoid this?

Update 20161110 - original answer below

Also, check out this answer for a different approach.

Original answer

This is actually possible.

But not directly, the way to do it is to create a second auth reference and use that to create users:

var config = {apiKey: "apiKey",
    authDomain: "",
    databaseURL: ""};
var secondaryApp = firebase.initializeApp(config, "Secondary");

secondaryApp.auth().createUserWithEmailAndPassword(em, pwd).then(function(firebaseUser) {
    console.log("User " + firebaseUser.uid + " created successfully!");
    //I don't know if the next statement is necessary 

If you don't specify which firebase connection you use for an operation it will use the first one by default.

Source for multiple app references.


For the actual creation of a new user, it doesn't matter that there is nobody or someone else than the admin, authenticated on the second auth reference because for creating an account all you need is the auth reference itself.

The following hasn't been tested but it is something to think about

The thing you do have to think about is writing data to firebase. Common practice is that users can edit/update their own user info so when you use the second auth reference for writing this should work. But if you have something like roles or permissions for that user make sure you write that with the auth reference that has the right permissions. In this case, the main auth is the admin and the second auth is the newly created user.

Update 20161108 - original answer below

Firebase just released its firebase-admin SDK, which allows server-side code for this and other common administrative use-cases. Read the installation instructions and then dive into the documentation on creating users.

original answer

This is currently not possible. Creating an Email+Password user automatically signs that new user in.

I just created a Firebase Function that triggers when a Firestore document is Created (with rules write-only to admin user). Then use admin.auth().createUser() to create the new user properly.

export const createUser = functions.firestore
.onCreate(async (snap, context) => {
    const userId = context.params.userId;
    const newUser = await admin.auth().createUser({
        disabled: false,
        displayName: snap.get('displayName'),
        email: snap.get('email'),
        password: snap.get('password'),
        phoneNumber: snap.get('phoneNumber')
    // You can also store the new user in another collection with extra fields
    await admin.firestore().collection('users').doc(newUser.uid).set({
        uid: newUser.uid,
        name: newUser.displayName,
        phoneNumber: newUser.phoneNumber,
        otherfield: snap.get('otherfield'),
        anotherfield: snap.get('anotherfield')
    // Delete the temp document
    return admin.firestore().collection('newUsers').doc(userId).delete();

You can Algo use functions.https.onCall()

exports.createUser= functions.https.onCall((data, context) => {
    const uid = context.auth.uid; // Authorize as you want
    // ... do the same logic as above

calling it.

const createUser = firebase.functions().httpsCallable('createUser');
createUser({userData: data}).then(result => {
    // success or error handling

I got André's very clever workaround working in Objective-C using the Firebase iOS SDK:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"];
FIROptions *secondaryAppOptions = [[FIROptions alloc] initWithContentsOfFile:plistPath];
[FIRApp configureWithName:@"Secondary" options:secondaryAppOptions];
FIRApp *secondaryApp = [FIRApp appNamed:@"Secondary"];
FIRAuth *secondaryAppAuth = [FIRAuth authWithApp:secondaryApp];

                           completion:^(FIRUser * _Nullable user, NSError * _Nullable error) {
                                [secondaryAppAuth signOut:nil];

Update for Swift 4

I have tried a few different options to create multiple users from a single account, but this is by far the best and easiest solution.

Original answer by Nico

First Configure firebase in your AppDelegate.swift file

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure(name: "CreatingUsersApp", options:!.options)

    return true

Add the following code to action where you are creating the accounts.

            if let secondaryApp = "CreatingUsersApp") {
                let secondaryAppAuth = Auth.auth(app: secondaryApp)

                // Create user in secondary app.
                secondaryAppAuth.createUser(withEmail: email, password: password) { (user, error) in
                    if error != nil {
                    } else {
                        //Print created users email.

                        //Print current logged in users email.
                        print(Auth.auth().currentUser?.email ?? "default")

                        try! secondaryAppAuth.signOut()


You can use firebase function for add users.

const functions = require('firebase-functions');
const admin = require('firebase-admin');

const cors = require('cors')({
origin: true,
exports.AddUser = functions.https.onRequest(( req, res ) => {
// Grab the text parameter.

cors( req, res, ()  => {
    let email  =;
    let passwd = req.body.passwd;
    let role   = req.body.role;
    const token = req.get('Authorization').split('Bearer ')[1];

            (decoded) => { 
             // return res.status(200).send(  decoded )
             return creatUser(decoded);
    .catch((err) => {
            return res.status(401).send(err) 

    function creatUser(user){
          email: email,
          emailVerified: false,
          password: passwd,
          disabled: false
        .then((result) => {
           return res.status(200).send(result);
        }).catch((error) => {
           return res.status(400).send(error.message);


The Swift version:


// Creating a second app to create user without logging in
FIRApp.configure(withName: "CreatingUsersApp", options: FIRApp.defaultApp()!.options)

if let secondaryApp = FIRApp(named: "CreatingUsersApp") {
    let secondaryAppAuth = FIRAuth(app: secondaryApp)

Here is a Swift 3 adaptaion of Jcabrera's answer :

let bundle = Bundle.main
        let path = bundle.path(forResource: "GoogleService-Info", ofType: "plist")!
        let options = FIROptions.init(contentsOfFile: path)
        FIRApp.configure(withName: "Secondary", options: options!)
        let secondary_app = FIRApp.init(named: "Secondary")
        let second_auth = FIRAuth(app : secondary_app!)
        second_auth?.createUser(withEmail: self.username.text!, password: self.password.text!)
            (user,error) in
            print(FIRAuth.auth()?.currentUser?.email ?? "default")

If you are using Polymer and Firebase (polymerfire) see this answer:

Essentially you create a secondary <firebase-app> to handle the new user registration without affecting the current user.

Swift 5: Simple Solution

First store the current user in a variable called originalUser

let originalUser = Auth.auth().currentUser

Then, in the completion handler of creating a new user, use the updateCurrentUser method to restore the original user

Auth.auth().updateCurrentUser(originalUser, completion: nil)

Android solution (Kotlin):

1.You need FirebaseOptions BUILDER(!) for setting api key, db url, etc., and don't forget to call build() at the end

2.Make a secondary auth variable by calling FirebaseApp.initializeApp()

3.Get instance of FirebaseAuth by passing your newly created secondary auth, and do whatever you want (e.g. createUser)

    // 1. you can find these in your project settings under general tab
    val firebaseOptionsBuilder = FirebaseOptions.Builder()
    firebaseOptionsBuilder.setApplicationId("YOUR_APPLICATION_ID") //not sure if this one is needed
    val firebaseOptions =

    // indeterminate progress dialog *ANKO*
    val progressDialog = indeterminateProgressDialog(resources.getString(R.string.progressDialog_message_registering))

    // 2. second auth created by passing the context, firebase options and a string for secondary db name
    val newAuth = FirebaseApp.initializeApp([email protected], firebaseOptions, Constants.secondary_db_auth)
    // 3. calling the create method on our newly created auth, passed in getInstance
    FirebaseAuth.getInstance(newAuth).createUserWithEmailAndPassword(email!!, password!!)
    .addOnCompleteListener { it ->

        if (it.isSuccessful) {

            // 'it' is a Task<AuthResult>, so we can get our newly created user from result
            val newUser = it.result.user

            // store wanted values on your user model, e.g. email, name, phonenumber, etc.
            val user = User()
   = email
   = name
            user.created = Date().time
   = true
   = phone

            // set user model on /db_root/users/uid_of_created_user/, or wherever you want depending on your structure

            // send newly created user email verification link


            // sign him out
            // DELETE SECONDARY AUTH! thanks, Jimmy :D

        } else {


            try {

                throw it.exception!!

                // catch exception for already existing user (e-mail)
            } catch (e: FirebaseAuthUserCollisionException) {

                alert(resources.getString(R.string.exception_FirebaseAuthUserCollision), resources.getString(R.string.alertDialog_title_error)) {

                    okButton {

                        isCancelable = false






Here is a simple solution using web SDKs.

  1. Create a cloud function (
import admin from 'firebase-admin';
import * as functions from 'firebase-functions';

const createUser = functions.https.onCall((data) => {
  return admin.auth().createUser(data)
    .catch((error) => {
      throw new functions.https.HttpsError('internal', error.message)

export default createUser;
  1. Call this function from your app
import firebase from 'firebase/app';

const createUser = firebase.functions().httpsCallable('createUser');

createUser({ email, password })
  1. Optionally, you can set user document information using the returned uid.
createUser({ email, password })
  .then(({ data: user }) => {
    return database
        created: new Date(),

I faced the same problem, and I solved it with this way:

When the user login, I save the email and password in the shared preferences. And after creating the user, I login the user again with email and password that I have saved before.

    String currentEmail = MyApp.getSharedPreferences().getEmail();
    String currentPass = MyApp.getSharedPreferences().getPass();

    FirebaseAuth auth = FirebaseAuth.getInstance();
    auth.createUserWithEmailAndPassword(email, pass)
            .addOnCompleteListener(AddStudent.this, new OnCompleteListener<AuthResult>() {

                public void onComplete(@NonNull final Task<AuthResult> task) {

                    if (task.isSuccessful()) {
                        String currentEmail = MyApp.getSharedPreferences().getEmail();
                        String currentPass = MyApp.getSharedPreferences().getPass();

                        //Sign in again
                        auth.signInWithEmailAndPassword(currentEmail, currentPass)
                                .addOnCompleteListener(AddStudent.this, new OnCompleteListener<AuthResult>() {
                                    public void onComplete(@NonNull Task<AuthResult> task) {
                                        if (!task.isSuccessful()) {
                                            Log.e("RELOGIN", "FAILED");
                                        } else {
                                            Log.e("RELOGIN", "SUCCESS");