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

Facebook Authentication

Configuring Your Application

To get started with Facebook authentication, you need to first create a new Facebook application. Click the Add a New App button in the top right of that page and select iOS as your platform. Then choose an App ID and click Create New Facebook App ID. Select your app's category and click Create App ID.

Next, go to the Configure step of the quickstart. In order to use the Facebook SDK you must configure your .plist file:

  • In your .plist file, you must have the FacebookAppID and FacebookDisplayName keys set to your Facebook application ID and display name. You also need to add an item to URL Schemes under URL types. Check out the Facebook Getting Started Guide for more details.
  • Install the Facebook SDK and include it in your project. If you're using CocoaPods and Swift, make sure to add the use_frameworks! command at the top of your Podfile so you can import the SDKs directly in your .swift files.
  • In your AppDelegate file, you must handle redirects from Facebook to your application:
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>

@implementation AppDelegate

// ...

- (BOOL)application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    return [[FBSDKApplicationDelegate sharedInstance] application:application
                                    didFinishLaunchingWithOptions:launchOptions];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [FBSDKAppEvents activateApp];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

    return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                          openURL:url
                                                sourceApplication:sourceApplication
                                                       annotation:annotation];
}

@end
import FBSDKCoreKit
import FBSDKLoginKit

class AppDelegate : UIResponder, UIApplicationDelegate {

    // ...

    func application(application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        return FBSDKApplicationDelegate.sharedInstance()
            .application(application, didFinishLaunchingWithOptions: launchOptions)
    }


    func applicationDidBecomeActive(application: UIApplication) {
        FBSDKAppEvents.activateApp()
    }

    func application(application: UIApplication, openURL url: NSURL,
        sourceApplication: String?, annotation: AnyObject?) -> Bool {

        return FBSDKApplicationDelegate.sharedInstance()
            .application(application, openURL: url,
                sourceApplication: sourceApplication, annotation: annotation)
    }
}

After configuring your app, go to the Bundle Identifier step and enter your Bundle Identifier from XCode. It will look like com.firebase.exampleApp. Then click on Skip to Developer Dashboard in the last section of the quickstart.

Next you'll need to get your app credentials from Facebook. In your Facebook app configuration, click on the Settings tab on the left-hand navigation menu. Click on the Basic tab at the top of the page. Towards the top of this page, you will see your App ID and App Secret. Your App ID will be displayed in plain text and you can view your App Secret by clicking on the Show button and typing in your Facebook password. Copy these Facebook application credentials (App ID and Secret) in to the Login & Auth section in your App Dashboard.

Adding Contact Information

Facebook requires that you have a valid contact email specified in order to make your app available to all users. You can specify this email address from the same Basic tab within the Settings section. After you have provided your email, click on Save Changes. The last thing you need to do to approve your app is click on the Status & Review tab on the left-hand navigation menu and move the slider at the top of that page to the Yes position. When prompted with a popup, click Confirm. Your app will now be live and can be used with Firebase.

Authenticating Facebook users to your Firebase App

Once you have enabled Facebook authentication, you can take advantage of the Security and Firebase Rules to protect your data.

To log a user in, we'll need to retrieve the OAuth Access Token from Facebook. Once we have the access token, we can use authWithOAuthProvider:token:withCompletionBlock: to authenticate the user with Firebase. Below is one way to get an access token with read permissions from the Facebook SDK.

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

[facebookLogin logInWithReadPermissions:@[@"email"]
    handler:^(FBSDKLoginManagerLoginResult *facebookResult, NSError *facebookError) {

    if (facebookError) {
        NSLog(@"Facebook login failed. Error: %@", facebookError);
    } else if (facebookResult.isCancelled) {
        NSLog(@"Facebook login got cancelled.");
    } else {
        NSString *accessToken = [[FBSDKAccessToken currentAccessToken] tokenString];

        [ref authWithOAuthProvider:@"facebook" token:accessToken
            withCompletionBlock:^(NSError *error, FAuthData *authData) {

            if (error) {
                NSLog(@"Login failed. %@", error);
            } else {
                NSLog(@"Logged in! %@", authData);
            }
        }];
    }
}];
let ref = Firebase(url: "https://<YOUR-FIREBASE-APP>.firebaseio.com")
let facebookLogin = FBSDKLoginManager()

facebookLogin.logInWithReadPermissions(["email"], handler: {
    (facebookResult, facebookError) -> Void in

    if facebookError != nil {
        println("Facebook login failed. Error \(facebookError)")
    } else if facebookResult.isCancelled {
        println("Facebook login was cancelled.")
    } else {
        let accessToken = FBSDKAccessToken.currentAccessToken().tokenString

        ref.authWithOAuthProvider("facebook", token: accessToken,
            withCompletionBlock: { error, authData in

                if error != nil {
                    println("Login failed. \(error)")
                } else {
                    println("Logged in! \(authData)")
                }
        })
    }
})

The FAuthData object returned to your block contains the following fields:

FAuthData
Field Description Type
uid A unique user ID, intended as the user's unique key across all providers. NSString
provider The authentication method used, in this case: facebook. NSString
token The Firebase authentication token for this session. NSString
auth The contents of the authentication token, which will be available as the auth variable within your Security and Firebase Rules. NSDictionary
expires A timestamp, in seconds since the UNIX epoch, indicating when the authentication token expires. NSNumber
providerData A dictionary containing provider-specific data. NSDictionary
providerData[@"id"] The Facebook user's ID. This ID is unique to each Facebook application and cannot be used across different apps. NSString
providerData[@"accessToken"] The Facebook OAuth 2.0 access token granted by Facebook during user authentication. NSString
providerData[@"displayName"] The Facebook user's full name. NSString
providerData[@"email"] The Facebook user's primary email address as listed on their profile. Returned only if a valid email address is available, and the Facebook email permission was granted by the user. NSString
providerData[@"profileImageURL"] The URL of the Facebook user's profile picture. NSString
providerData[@"cachedUserProfile"] The Facebook user's raw profile, as specified by Facebook's user documentation. Note that the data included in this payload is generated by Facebook and may be changed by them at any time. NSDictionary

Security & Rules

Now that the client is logged in, your Security and Firebase Rules have access to their unique user id. The auth variable contains the following values:

auth Variable
Field Description Type
uid A unique user ID, intended as the user's unique key across all providers. String
provider The authentication method used, in this case: facebook. String

Here is an example of how to use the auth variable in your Security and Firebase Rules:

{
  "rules": {
    "users": {
      "$uid": {
        // grants write access to the owner of this user account whose uid must exactly match the key ($uid)
        ".write": "auth !== null && auth.uid === $uid",

        // grants read access to any user who is logged in with Facebook
        ".read": "auth !== null && auth.provider === 'facebook'"
      }
    }
  }
}
See the User Authentication and User Based Security articles for more details.
  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