Level: ★☆☆ tag: “iOS access Google, Facebook login” “Firebase Google” “Firebase Facebook” author: WYW Review: QiShare team


preface

The author recently investigated iOS access to Google and Facebook login, and will sort out two articles. And share the following:

  1. Create Google and Facebook apps;
  2. Access to Google, Facebook login process;
  3. Access to Google and Facebook login apis;
  4. Possible problems with Google and Facebook login.

First up, I’m going to share with you how to create Google and Facebook apps on Firebase.

Create Google apps on Firebase

1. The Firebase is introduced

Firebase is Google’s mobile platform that helps you quickly develop great applications and grow your business.

1.1 Personal understanding of Firebase

In terms of using Firebase, the author has investigated Google, Facebook, Twitter, Github and anonymous login. Firebase helps developers quickly integrate Google, Facebook, Twitter logins and more.

For example, the domestic Umeng open platform can help developers quickly access the common three-way login and sharing in China. Firebase can help developers quickly access foreign common three party login sharing.

In addition, In terms of authorized login, Firebase further encapsulates the access of three parties. The developer (server) can use the authorization information returned by the three parties to obtain the token information returned by Firebase open platform (JWT format). In this way, the developer (server) can only interact with the token information returned by Firebase platform to verify the validity of the three-party user authorization information.

Note: Due to the wall, Google and Facebook logins need to be in the scientific Internet environment to work properly.

The following author demonstrates the authorization process after logging in to Google and Facebook using Firebase. The schematic diagram is as follows. After clicking the Google login button, the user’s Google information is obtained. Then use the relevant information to further obtain the Google information corresponding to Firebase open platform. The Facebook login process is similar.

1.2 The author uses Firebase to access Google and Facebook login effect picture is as follows.

In the next section, I will share the process of creating an application on Firebase Open platform and enabling the appropriate login on Firebase Open platform.

2. Add projects and create applications on the Firebase open platform

2.1 openFirebase Open platform, you can log in using your Google account
2.2 Adding a Project
2.3 Click the created project and add the corresponding iOS and Android app
2.4 Enter required application information, such as BundleID, application name, and AppStoreID (optional), and download the configuration file GoogleService- info.plist
2.5 The values of CLIENT_ID and REVERSED_CLIENT_ID in the configuration file will be mainly used in our subsequent Google login
2.6 Enabling Google and Facebook Login

Open the app we created and go to Authtication-> Login Methods -> Enable Google and Facebook login

Note: (1) In the case of using Firebase to access Facebook login, copy the OAuth redirection URI displayed when Facebook is enabled. This redirection URI will be pasted into the valid OAuth jump URI of the application created on the Facebook platform.

The copy of the OAuth redirect URL is shown below

Note: (2) The content of the application ID and application key in the figure above must be consistent with the application NUMBER and application key generated by the application created by Facebook Open Platform. Otherwise, when users log in using Facebook authorization, the following error will be reported when using Firbase API to verify login information.

Error Domain=FIRAuthErrorDomain Code=17004 "Unsuccessful debug_token response from Facebook: {"error": {"message":"Error validating application. Invalid application ID.","type":"OAuthException","code": 190,"fbtrace_id":"A-bczlMKMvzVfRTnOSP21_B"}}" UserInfo={NSLocalizedDescription=Unsuccessful debug_token response from Facebook: {"error": {"message":"Error validating application. Invalid application ID."."type":"OAuthException"."code": 190,"fbtrace_id":"A-bczlMKMvzVfRTnOSP21_B"}}, FIRAuthErrorUserInfoNameKey=ERROR_INVALID_CREDENTIAL}
Copy the code

In the next part, I’ll cover creating apps, adding test users, and approving apps on Facebook’s open platform.

2. Build an app on Facebook’s open platform

1. Build apps on Facebook’s open platform

1.1 openFacebook Open PlatformLogin with your Facebook account and password
1.2 Adding a new application, fill in the following information
1.3 Add basic information about the Settings of the new application
1.3.1 Fill in the privacy Policy URL, Terms of Service URL, iOS Bunde ID, Android package name, package signature, class name and other information
1.4 Fill in a valid OAuth jump URI in the Product Facebook Login -> Settings for the Facebook application you create, as mentioned in 2.6 of Part 1 of this article.

2. Enter a test user in the application

2.1 Add a test user in the Test User section of Creating an application user
2.2 Click the edit button on the right of the test user to change the account and password of the test user
2.3 Use the default email address for the user account. The password is specified in 1.4.2

3. Application review

3.1 Application Review Application
3.2 Related to application review
3.3 Click the application for Application Approval (the application number should be operated first and then changed to Publish under Development)
3.4 Audit time is 2 to 3 days

In the next part, I will share the process of logging in to Google and Facebook using Firebase.

3. Use Firebase to access Google and Facebook login

1. Integration mode

1.1 Log in to Google and Facebook through Cocoapods

2. Firebase related documents and integration process

2.1 Easily add login services to iOS apps using FirebaseUI
2.2 The author enters the following in the project’s Podfile

You can also specify the specific version number of Firebase according to your needs. FirebaseUI’s latest available version is 8.4.1 during my research

#	pod 'FirebaseUI/Auth'
	pod 'FirebaseUI/Google'
	pod 'FirebaseUI/Facebook'
Copy the code

You can also specify the version number as follows.

# pod 'FirebaseUI/Auth', '~> 8.4.1'
pod 'FirebaseUI/Google', '~> 8.4.1'
pod 'FirebaseUI/Facebook', '~> 8.4.1'
Copy the code

When I looked at the document again, I found that the pod contents can be changed as follows, and that the Pods file takes up the smallest amount of memory:

Pod 'Firebase/Auth', '~> 6.16.0' pod 'GoogleSignIn', '~> 5.0.2' pod 'FBSDKLoginKit', '~>6.0.0'Copy the code

3. Log in to Firebase from Google

3.1 Project Configuration Google Login

Required for normal use of Google login

  1. In the Firebase console, open the Authentication section and enable the Google Login service.
  2. In your Xcode project, TARGETS-> Info -> URL Types -> URL Schemes add your reverse client ID to the URL schema. You can be inGoogleService-Info.plistThe value corresponding to REVERSED_CLIENT_ID is found in the file.

3.2 Drag and drop the configuration file GoogleService- info.plist downloaded from Firebase open platform into the project
3.3 Initialize the Firebase SDK when the application starts
#import <Firebase.h>

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

	// Initialize Firebase configuration
	[FIRApp configure];
	[GIDSignIn sharedInstance].clientID = [FIRApp defaultApp].options.clientID;
    // Other code...
    return YES;
}
Copy the code
3.4 Google login needs to be handled in the following proxy method
3.4.1 Proxy methods in the appdelegate. m file
- (BOOL)application:(nonnull UIApplication *)application
            openURL:(nonnull NSURL *)url
            options:(nonnull NSDictionary<NSString *, id> *)options {
    
    return [[GIDSignIn sharedInstance] handleURL:url];
}

/ / ios (4.2, 9.0)
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation {
    if ([url.absoluteString containsString:[FIRApp defaultApp].options.clientID]) {
        return [[GIDSignIn sharedInstance] handleURL:url];
    }
    return NO;
}
Copy the code
The proxy method in 3.4.2 scenedelegate. m
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts  API_AVAILABLE(ios(13.0)) {UIOpenURLContext *openURLContext = URLContexts.allObjects.firstObject;
    if([openURLContext.URL.absoluteString containsString:[FIRApp defaultApp].options.clientID]) { [[GIDSignIn sharedInstance] handleURL:openURLContext.URL]; }}Copy the code
3.5 Code related to Google login button and code related to handling Google login failure result
#import <GoogleSignIn/GoogleSignIn.h>


      

// Set the proxy
[GIDSignIn sharedInstance].delegate = self;
// Must be set otherwise Crash will occur
[GIDSignIn sharedInstance].presentingViewController = self;

// Google login button wrapped in Firebase
GIDSignInButton *gidSignInBtn = [GIDSignInButton new];
gidSignInBtn.frame = CGRectMake(20.0.120.0.100.0.40.0);
gidSignInBtn.center = self.view.center;
[self.view addSubview:gidSignInBtn];


// Implement the proxy method
- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error {
    
    if(! error) {NSLog(User ID: %@, user.userID);
        
        GIDAuthentication *authentication = user.authentication;
        FIRAuthCredential *credential =
        [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken
                                         accessToken:authentication.accessToken];
        NSLog(@ "the credential Provider: % @", credential.provider);
        // Firebase authentication
        // Summary
        // Asynchronously signs in to Firebase with the given 3rd-party credentials (e.g. a Facebook login Access Token, a Google ID Token/Access Token pair, etc.) and returns additional identity provider data.
        // Log in to Firebase asynchronously
        [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
            if (error) {
                NSLog(Error message: %@, error.debugDescription);
            }
            if(! authResult) {NSLog(@" Authorization result is empty");
                return;
            }
            NSLog(@ "Firebase uid: % @", authResult.user.uid);
            
            // Used to obtain the Firebase token information of the login user and submit it to the server for verification
            [[FIRAuth auth].currentUser getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
                if (error) {
                    
                    NSLog(Error obtaining current token: %@, error);
                    return;
                }
                // Send token to your backend via HTTPS
                NSLog(Firebase user token info: %@, token);
           }];
            /** * credential Provider [95438:3699395] Google.com * 2020-03-06 20:48:47.914463+0800 FirebaseDemo[95438:3699395] Firebase UID: Ma4dqHEO7JZm ************QVE3 * 2020-03-06 21:21:22.486530+0800 FirebaseDemo[95931:3798238] Firebase Current user token Information: eyJhbGciOiJSUzI1NiIsImtpZCI6IjhjZjBjNjQyZDQ.*********4ZTRiZDc5OTkzOTZiNTY3NDAiLCJ0eX*********vbSJ9fQ.pvyaaG2dKKDH4CxO4VG Iq_jcwDnmP * * * * * * * * * * * * gQhHE - j - W / / the content of this part of the token is JWT format information * /
        }];
    } else {
        NSLog(@ "% @", error.debugDescription);
        self.userInfoLabel.text = error.debugDescription; }}Copy the code

In the above code, when Firebase provides us with a good GIDSignInButton, the Google login process will be executed. The result of successful or unsuccessful login is – (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error Callback in the proxy method of.

4. Firebase login to Facebook

4.1 Project Configuration Facebook Login
4.1.1 Configuring the Facebook AppID, URL Scheme, and FacebookDisplayName

In the info. plist file, configure the following FacebookAppID (CFBundleURLSchemes) and the name of Facebook access to display when using Facebook access (the value control for FacebookDisplayName).

Note:

The value of FacebookAppID should be the application number of the application we created on Facebook. If the application number is 12345678, the value of FacebookAppID should be 12345678.

CFBundleURLSchemes have fb append the application number of our Facebook apps, if 12345678 is CFBundleURLSchemes have fb12345678.

<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>fb8554384xxxxxxxx</string> </array> </dict> </array> <key>FacebookAppID</key> <string>8554384xxxxxxxx</string> <key>FacebookDisplayName</key> <string>FirebaseDemo</string>
Copy the code

If CFBundleURLSchemes are not filled in, the application crashes and reports the following problem.

2020-03-05 13:07:46.219473+0800 FirebaseDemo[11204:2947177] *** Terminating app due to uncaught exception ‘InvalidOperationException’, reason: ‘fb8554384xxxxxxxx is not registered as a URL scheme. Please add it in your Info.plist’

4.1.2 configuration LSApplicationQueriesSchemes

Fill in the following Facebook whitelist in the info.plist file; otherwise, you cannot jump from the app to the Facebook app. The phenomenon of not filling in the Facebook whitelist is that even if the mobile phone has Facebook application installed, it still does not prompt to jump to Facebook authorized login. Instead, a web page will pop up to authorize login.


<key>LSApplicationQueriesSchemes</key> <array> <string>fbapi</string> <string>fbapi20130214</string> <string>fbapi20130410</string> <string>fbapi20130702</string> <string>fbapi20131010</string> <string>fbapi20131219</string> <string>fbapi20140410</string> <string>fbapi20140116</string> <string>fbapi20150313</string> <string>fbapi20150629</string> <string>fbapi20160328</string> <string>fbauth</string> <string>fbauth2</string> <string>fbshareextension</string> </array>
Copy the code

I’ve tried using the following short whitelist on Facebook.

<string>fbauth</string> <string>fbauth2</string> 
Copy the code
4.2 When the application starts, call the code that prepares to use the Facebook SDK and initializes the Facebook SDK
#import <FBSDKLoginKit/FBSDKLoginKit.h>

 // To use the Facebook SDK, the following method should be called
[[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
/ / register FacebookAppID
[FBSDKSettings setAppID:kFacebookAppID];
Copy the code
4.3 Facebook login needs to be handled in the following proxy method

The following proxy method is used to remove the authorization view from the previous mode when Facebook is installed on the phone, when jumping from our app to Facebook and then from Facebook back to our app.

4.3.1 Proxy methods in the appdelegate. m file

- (BOOL)application:(nonnull UIApplication *)application
            openURL:(nonnull NSURL *)url
            options:(nonnull NSDictionary<NSString *, id> *)options {
    
    if (@available(iOS 9.0, *)) {
        return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
    } else {
        // Fallback on earlier versions}}/ / ios (4.2, 9.0)
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation {
    if ([url.absoluteString containsString:kFacebookAppID]) {
        return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
    }
    return NO;
}
Copy the code
The proxy method in 4.3.2 scenedelegate. m
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts  API_AVAILABLE(ios(13.0)) {UIOpenURLContext *openURLContext = URLContexts.allObjects.firstObject;
    if (openURLContext) {
        if ([openURLContext.URL.absoluteString containsString:kFacebookAppID]) {
             [[FBSDKApplicationDelegate sharedInstance] application:UIApplication.sharedApplication openURL:openURLContext.URL sourceApplication:openURLContext.options.sourceApplication annotation:openURLContext.options.annotation];
            return; }}}Copy the code
4.4 Code related to Facebook login button and code related to handling Facebook login failure result
#import "FBSDKLoginKit.h"


      

// The Firebase Facebook login button
FBSDKLoginButton *fbLoginBtn = [FBSDKLoginButton new];
fbLoginBtn.frame = CGRectMake(20.0.100.0.120.0.40.0);
fbLoginBtn.center = self.view.center;
fbLoginBtn.delegate = self;
[self.view addSubview:fbLoginBtn];

// FBSDKLoginButtonDelegate delegate method
- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error {
    
    if (error) {
        NSLog(Error message: %@, error);
    } else {
        FIRAuthCredential *credential =
        [FIRFacebookAuthProvider credentialWithAccessToken:result.token.tokenString];
        NSLog(@ "the credential Provider: % @", credential.provider);
        // Firebase authentication
        // Summary
        // Asynchronously signs in to Firebase with the given 3rd-party credentials (e.g. a Facebook login Access Token, a Google ID Token/Access Token pair, etc.) and returns additional identity provider data.
        // Log in to Firebase asynchronously
        [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
            if (error) {
                NSLog(Error message: %@, error.debugDescription);
            }
            if(! authResult) {NSLog(@" Authorization result is empty");
                return;
            }
            NSLog(@ "Firebase uid: % @", authResult.user.uid);
            
            
            
            /** * 2020-03-06 20:35:42.995671+0800 FirebaseDemo[95438:3699395] token info: 
      
        * 2020-03-06 20:35:45.301482+0800 FirebaseDemo[95438:3699395] Firebase UID: X8U372A8**************** s3S1 * 2020-03-06 21:22:49.582470+0800 FirebaseDemo[95931:3798238] Firebase Current user token Information: eyJhbGc*******************************************************AiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoi546L5rC45pe6IiwicGljdHVyZ SI6Imh0dHBzOi8vZ3JhcGguZmFjZWJvb2suY29tLzEwMTAyNzQ5NDgxOTk4My9wa*******************************************************2 tlbi5nb29nbGUuY29tL2Zpci1kZW1vLThkZj*******************************************************DM1MDA5NjgsInVzZXJfaWQiOiJYOF UzNzJBOG*******************************************************nlCdzNnS01nMXZ6czNzMSIsImlhdCI6MTU4MzUwMDk2OCwiZXhwIjoxNT gzNTA0NTY4LCJmaXJlYmFzZSI6eyJpZGVudGl0aWVzIjp7ImZhY2Vib29rLmNvbSI6WyIxMDEwMjc0OTQ4MTk5ODMiXX0sInNpZ25faW5fcHJvdmlkZXIiOi JmYWNlYm9vay5jb20ifX0.VuhMUV_hr9Bc0Alrv2MS1X*******************************************************omeMXd5ebEe_FtKXEvSpp DV8TN66p-*******************************************************lZpe-*************************************************** ****f-fyZ0lEK-p0PWB96WMKKY7jeVvPo_LR89u88kvjf7C-*******************************************************TWJmEYCMLqqtw9A * /
      
            // This part of token information is in JWT format
        }];
        NSLog(Token info: %@, result.token);
        self.userInfoLabel.text = [NSString stringWithFormat:Token info: %@, result.token.tokenString]; }}// This proxy method is called when the Facebook Log Out button is clicked
- (void)loginButtonDidLogOut:(FBSDKLoginButton *)loginButton {
    
    NSLog(@" Log out");
}
Copy the code

At present, we have obtained the token information returned by the third-party App and Firebase token information after the third-party login authorization is successful. We can use the Firebase token information to verify the validity of the relevant information on the server.

Programmatic authentication

I don’t know much about the development of the server, I saw this website

Authentication ID token is probably a document that can be used by the server to verify the validity of the client’s authorization information (the authorization information obtained by the client clicking on Google or Facebook login).

Five, the summary

In this paper, the author recorded the use of Firebase integrated Google, Facebook login open platform project creation, project related configuration process and Firebase provided Google, Facebook login related code; However, we may consider that we do not want to add irrelevant code and resource files and the resulting increase in the volume of some packages, or we may consider that we want to separately access the login of Google and Facebook to slightly reduce the compilation time, at this time we can also choose to directly access the SDK provided by Google and Facebook. In the next article, I’ll share the SDK and related code for logging directly into Google and Facebook.

Refer to study website

  • Start using Firebase authentication on iOS
  • Use Google Login service for authentication on iOS
  • Validate the ID token
  • Add the Firebase Admin SDK to your server
  • Programmatic authentication
  • Use Twitter for authentication on iOS
  • Google Sign-In for iOS
  • Facebook Login for iOS – Quick Start
  • How do I convert a video to Gif format

To learn more about iOS and related new technologies, please follow our official account:

Xiaobian wechat: You can add and pull into “QiShare Technical Exchange Group”.

QiShare(Simple book) QiShare(digging gold) QiShare(Zhihu) QiShare(GitHub) QiShare(CocoaChina) QiShare(StackOverflow) QiShare(wechat public account)

Recommended articles: Today we are going to talk about WebSocket (iOS/Golang) with Swift Bessel curve drawing Swift 5.1 (11) – Method Swift 5.1 (10) – Properties iOS App backstage keepalive Strange Dance Weekly