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

Google Authentication

Configuring Your Application

To get started with Google authentication, start by following the Google Sign-In Getting Started Guide, which walks you through the following:

  • Installing the SDK. CocoaPods users can include pod 'Google/SignIn' in their Podfile to download the SDK. Swift users need to include #import <Google/SignIn.h> in the app's project-Bridging-Header.h file.
  • Enabling Google Sign-In for your app. This process will create a new application and Client ID for your app. After you've created your application, select Google Sign-In and click the button to generate the configuration files. Download the generated GoogleService-Info.plist and drag it into the root of your application.
  • Configuring URL schemes for the Reversed Client ID and the Bundle ID.

After configuring your Google application, head on over to the Login & Auth section in your App Dashboard. Enable Google authentication and then copy your Google application Client ID into the appropriate inputs. The secret key is not needed. You can find your Google application's Client ID in the GoogleService-Info.plist.

In your AppDelegate, you must initialize Google Sign-In and handle Incoming URLs. Google sends information back to an application through an incoming URL, so make sure you've configured the URL schemes properly.

#import <Google/SignIn.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  NSError* configureError;
  [[GGLContext sharedInstance] configureWithError: &configureError];
  NSAssert(!configureError, @"Error configuring Google services: %@", configureError);

  return YES;
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
  return [[GIDSignIn sharedInstance] handleURL:url
                             sourceApplication:sourceApplication
                                    annotation:annotation];
}

@end
// Don't for get to import Google/SignIn in your bridging header with
// #import <Google/SignIn.h>

class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(application: UIApplication,
      didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Configure Sign-In
        var configureError: NSError?
        GGLContext.sharedInstance().configureWithError(&configureError)
        assert(configureError == nil, "Error configuring Google services: \(configureError)")

        return true
    }

    // Handle incoming URLs
    func application(application: UIApplication,
      openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
        return GIDSignIn.sharedInstance().handleURL(url,
            sourceApplication: sourceApplication,
            annotation: annotation)
    }

}

Authenticating Google users to your Firebase App

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

To log a user in, you will need a Google OAuth access token returned by the login flow provided by the Google SDK. 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 from the Google SDK.

// In your ViewController.h file
#import <Google/SignIn.h>

@interface ViewController : UIViewController<GIDSignInUIDelegate>
@property (nonatomic, strong) Firebase *ref;
@end

// In your ViewController.m file
@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.ref = [[Firebase alloc] initWithUrl:@"https://<YOUR-FIREBASE-APP>.firebaseio.com"];

  // Setup delegates
  GIDSignIn *googleSignIn = [GIDSignIn sharedInstance];
  googleSignIn.delegate = self;
  googleSignIn.uiDelegate = self;

  // Attempt to sign in silently, this will succeed if
  // the user has recently been authenticated
  [googleSignIn signInSilently];
}

// Wire up to a button tap
- (void)authenticateWithGoogle {
  [[GIDSignIn sharedInstance] signIn];
}

- (void)signOut {
  [[GIDSignIn sharedInstance] signOut];
  [self.ref unauth];
}

// Implement the required GIDSignInDelegate methods
- (void)signIn:(GIDSignIn *)signIn
didSignInForUser:(GIDGoogleUser *)user
     withError:(NSError *)error {
    if (error == nil) {
      [ref.authWithOAuthProvider: @"google" token:user.authentication.accessToken withCompletionBlock:^(NSError *error, FAuthData *authData) {
        if (error) {
            // Error authenticating with Firebase with OAuth token
        } else {
            // User is now logged in!
            NSLog(@"Successfully logged in! %@", authData);
        }
      }];
    }
}

// Implement the required GIDSignInDelegate methods
// Unauth when disconnected from Google
- (void)signIn:(GIDSignIn *)signIn
didDisconnectWithUser:(GIDGoogleUser *)user
     withError:(NSError *)error {
       [self.ref unauth];
}

@end
class ViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate {

    var ref: Firebase!

    override func viewDidLoad() {
        super.viewDidLoad()
        ref = Firebase(url: "https://<YOUR-FIREBASE-APP>.firebaseio.com/")

        // Setup delegates
        GIDSignIn.sharedInstance().delegate = self
        GIDSignIn.sharedInstance().uiDelegate = self

        // Attempt to sign in silently, this will succeed if
        // the user has recently been authenticated
        GIDSignIn.sharedInstance().signInSilently()
    }

    // Wire up to a button tap
    func authenticateWithGoogle(sender: UIButton) {
        GIDSignIn.sharedInstance().signIn()
    }

    func signOut() {
      GIDSignIn.sharedInstance().signOut()
      ref.unauth()
    }

    // Implement the required GIDSignInDelegate methods
    func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
      withError error: NSError!) {
        if (error == nil) {
          // Auth with Firebase
          ref.authWithOAuthProvider("google", token: user.authentication.accessToken, withCompletionBlock: { (error, authData) in
            // User is logged in!
          })
        } else {
          // Don't assert this error it is commonly returned as nil
          println("\(error.localizedDescription)")
        }
    }

    // Implement the required GIDSignInDelegate methods
    // Unauth when disconnected from Google
    func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!,
      withError error: NSError!) {
        ref.unauth();
    }
}

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: google. 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 Google user's ID. NSString
providerData[@"accessToken"] The Google OAuth 2.0 access token granted by Google during user authentication. NSString
providerData[@"displayName"] The Google user's full name. NSString
providerData[@"email"] The Google user's primary email address as listed on their profile. Returned only if a valid email address is available, and the Google email permission was granted by the user. NSString
providerData[@"profileImageURL"] The URL of the Google user's profile picture. NSString
providerData[@"cachedUserProfile"] The Google user's raw profile, as specified by Google's user documentation. Note that the data included in this payload is generated by Google 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 verified 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: google. 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 Google
        ".read": "auth !== null && auth.provider === 'google'"
      }
    }
  }
}
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