You're viewing the legacy docs. They are deprecated as of May 18, 2016.
These docs are for version 2.5.1 and below of the Objective-C SDK. Go to our current docs, or see our iOS migration guide.

Objective-C and Swift iOS Guide

User Authentication

Firebase makes authentication easy. It can integrate with your existing login server, or authenticate users with only client-side code. It has built-in functionality for email & password, and third-party providers such as Facebook, Twitter, GitHub, and Google.

Overview

Most applications need to know the identity of a user. Knowing a user's identity allows an app to provide a customized experience and grant them permissions to access their data. The process of proving a user's identity is called authentication. Firebase provides a full set of authentication options out-of-the-box.

When a user authenticates to a Firebase app, three things happen:

  • Information about the user is returned in callbacks on the client device. This allows you to customize your app's user experience for that specific user.
  • The user information returned contains a uid (a unique ID), which is guaranteed to be distinct across all providers, and to never change for a specific authenticated user.
  • The value of the auth variable in your app's Security and Firebase Rules becomes defined. This variable is null for unauthenticated users, but for authenticated users it is an object containing the user's unique (auth.uid) and potentially other data about the user. This allows you to securely control data access on a per-user basis.

Firebase apps have built-in support for logging in with email & password, social login providers such as Facebook, Google, Twitter, and GitHub, and single-session anonymous login. Apps that use Firebase's built-in auth services can handle user login entirely with client-side code, saving you time and the headache of operating your own backend.

If you have existing server-side authentication or single sign-on, you can also easily integrate it with Firebase. Download one of our helper libraries to generate authentication tokens on your own servers.

Simple Login Deprecated

Login is now a core feature of Firebase clients. Simple Login has been deprecated and documentation for this client is now available on Github.

Setup an Authentication Provider

Here is a list of the providers that Firebase applications support. Select the one that fits your needs, and follow the provider-specific steps to set it up.

Platform Description
Custom Generate your own login tokens. Use this to integrate with existing authentication systems. You can also use this to authenticate server-side workers.
Email & Password Let Firebase manage passwords for you. Register and authenticate users by email & password.
Anonymous Build user-centric functionality without requiring users to share their personal information. Anonymous authentication generates a unique identifier for each user that lasts as long as their session.
Facebook Authenticate users with Facebook by writing only client-side code.
Twitter Authenticate users with Twitter by writing only client-side code.
GitHub Authenticate users with GitHub by writing only client-side code.
Google Authenticate users with Google by writing only client-side code.

Enabling Providers

Next, you need to enable the provider for your Firebase app.

  1. Go to the Account Dashboard.
  2. Select your Firebase app.
  3. Choose the Login & Auth tab.
  4. Find the Authentication Providers section.
  5. Select a tab for a provider and enable authentication.
  6. If you're using a social login provider, like Facebook, copy your client ID and secret into the form.

The Firebase app is all set up for your provider. It's time to code.

Monitoring Authentication

To listen for changes in the authentication state, attach an event observer with observeAuthEventWithBlock. If there is no user currently authenticated, authData will be nil.

Firebase *ref = [[Firebase alloc] initWithUrl:@"https://<YOUR-FIREBASE-APP>.firebaseio.com"];

[ref observeAuthEventWithBlock:^(FAuthData *authData) {
    if (authData) {
        // user authenticated
        NSLog(@"%@", authData);
    } else {
        // No user is signed in
    }
}];
let ref = Firebase(url: "https://<YOUR-FIREBASE-APP>.firebaseio.com")

ref.observeAuthEventWithBlock({ authData in
    if authData != nil {
        // user authenticated
        println(authData)
    } else {
        // No user is signed in
    }
})

You can also check the user's authentication state by calling the synchronous authData function:

Firebase *ref = [[Firebase alloc] initWithUrl:@"https://<YOUR-FIREBASE-APP>.firebaseio.com"];

if (ref.authData) {
    // user authenticated
    NSLog(@"%@", ref.authData);
} else {
    // No user is signed in
}
let ref = Firebase(url: "https://<YOUR-FIREBASE-APP>.firebaseio.com")

if ref.authData != nil {
    // user authenticated
    println(ref.authData)
} else {
    // No user is signed in
}

When adding an authentication event observer, Firebase will return a FirebaseHandle. You can use this this handle to stop listening to changes with removeAuthEventObserverWithHandle.

Firebase *ref = [[Firebase alloc] initWithUrl:@"https://<YOUR-FIREBASE-APP>.firebaseio.com"];
FirebaseHandle *handle = [ref observeAuthEventWithBlock:^(FAuthData *authData) { ... }];
[ref removeAuthEventObserverWithHandle:handle];
let ref = Firebase(url: "https://<YOUR-FIREBASE-APP>.firebaseio.com")
let handle = ref.observeAuthEventWithBlock({ authData in ... })
ref.removeAuthEventObserverWithHandle(handle)

Logging Users In

The code to authenticate a user varies by provider, but they all have similar signature. They all accept a completion block to handle errors and process the results of a successful login.

[ref authUser:@"jenny@example.com" password:@"correcthorsebatterystaple"
    withCompletionBlock:^(NSError *error, FAuthData *authData) {

    if (error) {
        // an error occurred while attempting login
    } else {
        // user is logged in, check authData for data
    }
}];
ref.authUser("jenny@example.com", password: "correcthorsebatterystaple") {
    error, authData in
    if error != nil {
        // an error occured while attempting login
    } else {
        // user is logged in, check authData for data
    }
}

Tokens issued to the authenticated users are valid for 24 hours by default. You can change this from the Login & Auth tab on the App Dashboard.

Logging Users Out

Calling unauth invalidates your user's token, and logs them out of your app:

[ref unauth];
ref.unauth()

Storing User Data

Internally, Firebase generates JWT auth tokens and creates authenticated sessions by calling authWithCustomToken:withCompletionBlock: with those tokens. Each user is assigned a uid (a unique ID), which is guaranteed to be distinct across all providers, and to never change for a specific authenticated user.

It does not store profile or user state in your Firebase database. To persist user data you must save it to your database. The completion block will return an FAuthData object. This FAuthData object contains unique information about the logged in user.

In the code sample below, we authenticate the user, and then store user data in the path https://<YOUR-FIREBASE-APP>.firebaseio.com/users/<uid>, where users/ is any arbitrary path to store user data, and <uid> represents the unique id obtained from the authentication data.

The authData variable contains all of the specific information about the user. The uid property on the FAuthData object provides a way to uniquely identify the user.

[ref authUser:@"jenny@example.com" password:@"correcthorsebatterystaple"
    withCompletionBlock:^(NSError *error, FAuthData *authData) {

    if (error) {
        // Something went wrong. :(
    } else {
        // Authentication just completed successfully :)

        // The logged in user's unique identifier
        NSLog(@"%@", authData.uid);

        // Create a new user dictionary accessing the user's info
        // provided by the authData parameter
        NSDictionary *newUser = @{
            @"provider": authData.provider,
            @"displayName": authData.providerData[@"displayName"]
        };

        // Create a child path with a key set to the uid underneath the "users" node
        // This creates a URL path like the following:
        //  - https://<YOUR-FIREBASE-APP>.firebaseio.com/users/<uid>
        [[[ref childByAppendingPath:@"users"]
               childByAppendingPath:authData.uid] setValue:newUser];
    }
}];
ref.authUser("jenny@example.com", password:"correcthorsebatterystaple") {
    error, authData in
    if error != nil {
        // Something went wrong. :(
    } else {
        // Authentication just completed successfully :)

        // The logged in user's unique identifier
        println(authData.uid)

        // Create a new user dictionary accessing the user's info
        // provided by the authData parameter
        let newUser = [
            "provider": authData.provider,
            "displayName": authData.providerData["displayName"] as? NSString as? String
        ]

        // Create a child path with a key set to the uid underneath the "users" node
        // This creates a URL path like the following:
        //  - https://<YOUR-FIREBASE-APP>.firebaseio.com/users/<uid>
        ref.childByAppendingPath("users")
           .childByAppendingPath(authData.uid).setValue(newUser)
    }
}

When a user is saved using the above code, the user's node in the database looks something like this:

{
  "users": {
    "6d914336-d254-4fdb-8520-68b740e047e4": {
      "displayName": "alanisawesome",
      "provider": "password"
    },
    "002a448c-30c0-4b87-a16b-f70dfebe3386": {
      "displayName": "gracehop",
      "provider": "password"
    }
  }
}

Since the user's uid property is unique, it is the recommended key for storing users.

Handling Errors

When your app calls an authentication method, you pass it a completion block. It is invoked if there are any errors during the authentication process.

All errors are of type NSError and have the code and description attributes.

In some cases you may want to explicitly check for specific errors to notify your user, or prompt them to login again. For example, if you're using email & password authentication, you would want to check for an invalid email or password:

[ref authUser:@"jenny@example.com" password:@"correcthorsebatterystaple"
    withCompletionBlock:^(NSError* error, FAuthData* authData) {

    if (error != nil) {
        // an error occurred while attempting login
        switch(error.code) {
            case FAuthenticationErrorUserDoesNotExist:
                // Handle invalid user
                break;
            case FAuthenticationErrorInvalidEmail:
                // Handle invalid email
                break;
            case FAuthenticationErrorInvalidPassword:
                // Handle invalid password
                break;
            default:
                break;
        }
    } else
        // User is logged in
    }
}];
ref.authUser("jenny@example.com", password: "correcthorsebatterystaple") {
    error, authData in
    if (error != nil) {
        // an error occurred while attempting login
        if let errorCode = FAuthenticationError(rawValue: error.code) {
            switch (errorCode) {
            case .UserDoesNotExist:
                println("Handle invalid user")
            case .InvalidEmail:
                println("Handle invalid email")
            case .InvalidPassword:
                println("Handle invalid password")
            default:
                println("Handle default situation")
            }
        }
    } else {
        // User is logged in
    }
}

Full Error Listing

Error Code Description
FAuthenticationErrorDeniedByUser The user did not authorize the application. This error can occur when the user has cancelled an OAuth authentication request.
FAuthenticationErrorEmailTaken The new user account cannot be created because the specified email address is already in use.
FAuthenticationErrorInvalidConfiguration The requested authentication provider is misconfigured, and the request cannot complete. Please confirm application configuration.
FAuthenticationErrorInvalidCredentials The specified authentication credentials are invalid. This may occur when credentials are malformed or expired.
FAuthenticationErrorInvalidEmail The specified email is not a valid email.
FAuthenticationErrorInvalidPassword The specified user account password is incorrect.
FAuthenticationErrorNetworkError An error occurred while attempting to contact the authentication server.
FAuthenticationErrorPreempted The current request was aborted by a new, incoming authentication request.
FAuthenticationErrorUnknown An unknown error occurred. Please refer to the error message and error details for more information.
FAuthenticationErrorUserDoesNotExist The specified user account does not exist.
FAuthenticationErrorInvalidProvider The requested authentication provider does not exist. Please consult the Firebase Authentication documentation for a list of supported providers.
FAuthenticationErrorProviderDisabled The requested authentication provider is disabled for this Firebase app.
FAuthenticationErrorProviderError A third-party provider error occurred. Please refer to the error message and error details for more information.
FAuthenticationErrorInvalidArguments The specified credentials are malformed or incomplete. Please refer to the error message, error details, and Firebase documentation for the required arguments for authenticating with this provider.
FAuthenticationErrorInvalidCredentials The specified authentication token is invalid. This can occur when the token is malformed, expired, or the secret that was used to generate it has been revoked.
  1. 1

    Next

    Installation & Setup

  2. 2

    Next

    Understanding Data

  3. 3

    Next

    Saving Data

  4. 4

    Next

    Retrieving Data

  5. 5

    Next

    Structuring Data

  6. 6

    Next

    Understanding Security

  7. 7

    Next

    User Authentication

  8. 8

    Next

    Offline Capabilities