如何在 OS X Cocoa 应用程序中使用 Google 授权用户

How to authorize user with Google in OS X Cocoa application

我正在使用 Firebase in my OS X application. I am trying to add Google Authentication. This is an example for iOS

问题是:如何在OS X 应用程序中获取Google OAuth 访问令牌?

可以在 Objective-C 中获取 Google OAuth 2 令牌。 GTMOAuth2。使用椰子:

pod 'GTMOAuth2'


GTMOAuth2 库需要应用程序类型为 other 的客户端 ID。可以在 Google 开发者控制台中创建一个:


这是描述如何使用此库的代码示例:

#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.");
                                                    }
                              }];
}

它会在第一次启动时创建带有 Google 授权页面的弹出窗口 window 并使用存储在钥匙串中的 "token"随后的运行。


优点

此授权方几乎可以与每个 Google 服务一起使用。

缺点

看起来它不能很容易地与 Firebase 集成。

Firebase 身份验证可以与 Google 集成,使用 GTMOAuth2 pod 在 OS X 上登录。

import Cocoa
import GTMOAuth2
import Firebase

class MainWindowController: NSWindowController {

let ref = Firebase(url: "https://xyz.firebaseio.com")

override func windowDidLoad() {
    super.windowDidLoad()


    let frameworkBundle = NSBundle(forClass: GTMOAuth2WindowController.self)
    let windowController = GTMOAuth2WindowController(scope: "", clientID: clientID, clientSecret: clientSecret, keychainItemName: keychainName, resourceBundle: frameworkBundle)
    windowController.signInSheetModalForWindow(window, delegate: self, finishedSelector: #selector(MainWindowController.didFinishWithAuth(windowController:auth:error:)))

}

func didFinishWithAuth(windowController wc:GTMOAuth2WindowController, auth: GTMOAuth2Authentication, error: NSError?) {
    if error != nil {
        print(error)
    } else {
        print(auth)
        ref.authWithOAuthProvider("google", token: auth.accessToken, withCompletionBlock: { err, auth in
            if err != nil {
                print(err)
            } else {
                print(auth)
            }
        })
      }
  }
}

有几点需要注意,正如上面提到的 brainless,您必须使用凭据管理器中的 other 选项创建一个 OAuth Api 密钥。您必须记住在您的 firebase 项目中将您的 clientID 列入白名单。

已更新

为最新版本的 Firebase 更新了代码。使用 Google(使用 OAuth)登录以使用 Firebase 进行身份验证。

func someFunc {
    let frameworkBundle = Bundle(for: GTMOAuth2WindowController.self)
    let windowController = GTMOAuth2WindowController(scope: "https://www.googleapis.com/auth/plus.me", clientID: YOUR_CLIENT_ID, clientSecret: YOUR_CLIENT_SECRET, keychainItemName: "OAuth2 APP_NAME: Google+", resourceBundle: frameworkBundle)

    guard let window = self.view.window else { return }

    windowController?.signInSheetModal(for: window, delegate: self, finishedSelector: #selector(didFinishWithAuth(windowController:auth:error:)))
}

  @objc func didFinishWithAuth(windowController:GTMOAuth2WindowController, auth: GTMOAuth2Authentication, error: NSError?) {
    if error != nil {
      print(error?.localizedDescription ?? String())
    } else {

      let credential = OAuthProvider.credential(withProviderID: GoogleAuthProviderID, accessToken: auth.accessToken)

        Auth.auth().signIn(with: credential) { (auth, error) in
          if let error = error {
            print(error.localizedDescription)
            return
          }

          // Successful sign in
      }
    }
  }