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.

User Authentication

Twitter Authentication

Configuring Your Application

If you have not already done so, create a new Twitter application.

After configuring your Twitter application, copy your Twitter application credentials (API Key and API Secret) to the Login & Auth section in your App Dashboard.

Authenticating Twitter users to your Firebase App

To log a user in with Twitter, we'll need to retrieve the OAuth token from Twitter. One way to do this is to download the two files TwitterAuthHelper.h and TwitterAuthHelper.m and use the example code below. They are also available in the example on Github. You will also need to include Accounts.framework and Social.framework

If the user has connected one or more Twitter accounts to their iOS device, we can prompt them to authorize the app. Since devices can have more than one Twitter account, we will need to provide a block that determines which account to log in. After the user has been authenticated with Twitter, signing them into your Firebase app can be triggered by:

Firebase *ref = [[Firebase alloc] initWithUrl:@"https://<YOUR-FIREBASE-APP>.firebaseio.com"];
TwitterAuthHelper *twitterAuthHelper = [[TwitterAuthHelper alloc] initWithFirebaseRef:ref
    apiKey:@"<YOUR-TWITTER-CONSUMER-KEY>"];
[twitterAuthHelper selectTwitterAccountWithCallback:^(NSError *error, NSArray *accounts) {
    if (error) {
        // Error retrieving Twitter accounts
    } else if ([accounts count] == 0) {
        // No Twitter accounts found on device
    } else {
        // Select an account. Here we pick the first one for simplicity
        ACAccount *account = [accounts firstObject];
        [twitterAuthHelper authenticateAccount:account withCallback:^(NSError *error, FAuthData *authData) {
            if (error) {
                // Error authenticating account
            } else {
                // User logged in!
            }
        }];
    }
}];
let ref = Firebase(url: "https://<YOUR-FIREBASE-APP>.firebaseio.com")
let twitterAuthHelper = TwitterAuthHelper(firebaseRef: ref, apiKey:"<YOUR-TWITTER-CONSUMER-KEY>")
twitterAuthHelper.selectTwitterAccountWithCallback { error, accounts in
    if error != nil {
        // Error retrieving Twitter accounts
    } else if accounts.count > 1 {
        // Select an account. Here we pick the first one for simplicity
        let account = accounts[0] as? ACAccount
        twitterAuthHelper.authenticateAccount(account, withCallback: { error, authData in
            if error != nil {
                // Error authenticating account
            } else {
                // User logged in!
            }
        })
    }
}

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: twitter. 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 Twitter user's ID. NSString
providerData[@"displayName"] The Twitter user's full name. NSString
providerData[@"username"] The Twitter user's screen name, handle, or alias. Twitter screen names are unique, but subject to change. NSString
providerData[@"profileImageURL"] The URL of the Twitter user's profile picture. NSString
providerData[@"cachedUserProfile"] The Twitter user's raw profile, as specified by Twitter's user documentation. Note that the data included in this payload is generated by Twitter and may be changed by them at any time. NSDictionary

Security and Firebase 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: twitter. 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 Twitter
        ".read": "auth !== null && auth.provider === 'twitter'"
      }
    }
  }
}
See the User Authentication and User Based Security articles for more details.

Authenticating with Multiple Accounts

Since many users have multiple Twitter accounts (personal, work, parody, etc.) we have to ensure that they can authenticate via any of the accounts they have access to. Below is some example code that demonstrates how we can use the TwitterAuthHelper to authenticate when a user has multiple Twitter accounts on his or her device.

// In your interface declaration, add this property
@interface TwitterLoginViewController : UIViewController<UIActionSheetDelegate>
@property TwitterAuthHelper *twitterAuthHelper;
@end

@implementation TwitterLoginViewController
- (void) authenticateWithTwitter {
    Firebase *ref = [[Firebase alloc] initWithUrl:@"https://<YOUR-FIREBASE-APP>.firebaseio.com"];
    self.twitterAuthHelper = [[TwitterAuthHelper alloc] initWithFirebaseRef:ref
        apiKey:@"<YOUR-TWITTER-CONSUMER-KEY>"];
    [self.twitterAuthHelper selectTwitterAccountWithCallback:^(NSError *error, NSArray *accounts) {
        if (error) {
            NSString *message = [NSString stringWithFormat:@"There was an error logging into Twitter: %@", [error localizedDescription]];
            [self showErrorAlertWithMessage:message];
        } else {
            [self handleMultipleTwitterAccounts:accounts];
        }
    }];
}

- (void) handleMultipleTwitterAccounts:(NSArray *)accounts {
    switch ([accounts count]) {
    case 0:
        // No account on device.
        break;

    case 1:
        // Single user system, go straight to login
        [self authenticateWithTwitterAccount:[acccounts firstObject]];
        break;

    default:
        // Handle multiple users
        [self selectTwitterAccount:accounts];
        break;
    }
}

- (void) authenticateWithTwitterAccount:(ACAccount *)account {
    [self.twitterAuthHelper authenticateAccount:account
        withCallback:^(NSError *error, FAuthData *authData) {
        if (error) {
            // Error authenticating account with Firebase
        } else {
            // User successfully logged in
            NSLog(@"Logged in! %@", authData);
        }
    }];
}

- (void) selectTwitterAccount:(NSArray *)accounts {
    // Pop up action sheet which has different user accounts as options
    UIActionSheet *selectUserActionSheet = [[UIActionSheet alloc] initWithTitle:@"Select Twitter Account" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
    for (ACAccount *account in accounts) {
      [selectUserActionSheet addButtonWithTitle:[account username]];
    }
    selectUserActionSheet.cancelButtonIndex = [selectUserActionSheet addButtonWithTitle:@"Cancel"];
    [selectUserActionSheet showInView:self.view];
}

- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *currentTwitterHandle = [actionSheet buttonTitleAtIndex:buttonIndex];

    for (ACAccount *account in self.twitterAuthHelper.accounts) {
        if ([currentTwitterHandle isEqualToString:account.username]) {
            [self authenticateWithTwitterAccount:account];
            return;
        }
    }
}
@end

You should now be able to authenthicate any one of mutiple Twitter accounts tied to a device!

Present your users with appropriate UI during login (for instance, UIActivityIndicatorView), and during error conditions (for instance, a UIAlertView).
  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