brainless brainless - 1 year ago 133
Objective-C Question

How to authorize user with Google in OS X Cocoa application

I am using Firebase in my OS X application. I am trying to add Google Authentication. This is an example for iOS.

Question is: How to obtain Google OAuth access token in OS X application?

Answer Source

It is possible to obtain Google OAuth 2 token in Objective-C with. GTMOAuth2. Using cocoapods:

pod 'GTMOAuth2'

GTMOAuth2 library needs client id with application type other. It is possible to create one in Google Developer Console:

enter image description here

This a code sample describing how to work with this lib:

#import "GTMOAuth2Authentication.h"
#import "GTMOAuth2WindowController.h"


- (void) applicationDidFinishLaunching:(NSNotification *) aNotification {
    GTMOAuth2Authentication * = [GTMOAuth2WindowController
               authForGoogleFromKeychainForName: @"where-to-store-token-in-a-keychain" 
                                       clientID: @"client-id"
                                   clientSecret: @"client-secret"];

    if (authorizer.canAuthorize) {
        NSLog(@"Your authorizer was restored from key chain and can be autorized. Authorozer: %@", authorizer);
    else {
        NSBundle * frameworkBundle = [NSBundle bundleForClass:[GTMOAuth2WindowController class]];
        GTMOAuth2WindowController * windowController;
        windowController = [GTMOAuth2WindowController controllerWithScope: @"" //scope url here, empty is just email and profile
                                                             clientID: clientID
                                                         clientSecret: clientSecret
                                                     keychainItemName: kKeychainItemName
                                                       resourceBundle: frameworkBundle];

        [windowController signInSheetModalForWindow: [self window]
                              completionHandler: ^(GTMOAuth2Authentication * auth, NSError * error) {
                                                    if (error == nil) {
                                                        authorizer = auth;
                                                        NSLog(@"Successfully signed in.");
                                                    } else {
                                                        NSLog(@"Failed to sign in.");

It will create pop-up window with Google authorization page inside on a first launch and use "token" stored in keychain for subsequent runs.


This authorizer can be used with almost every Google Service.


Looks like it can not be easily integrated with Firebase.