Login with Facebook

Top  Previous  Next

Backendless integrates with Facebook to support user authentication and login into a Backendless application with a Facebook account. Using the integration application developer can provide a way to skip the application registration step and allow users to use their Facebook identity to enter and experience the application. Backendless provides two ways to handle Facebook logins:

Easy Facebook Login - The Facebook SDK is not required on the client. The client application makes a Backendless API call to initiate the login and the user authenticates in a Facebook popup window.
Login with Facebook SDK - The client application uses the Facebook SDK to authenticate the user and then delegates to a Backendless API call to link the Facebook identity to a BackendlessUser instance.

Both approaches - Easy Login and Login with SDK, rely on the concepts and a configuration change described below.

Property Mapping

Backendless user objects may have their own set of user properties. As a result, when a user logs in using their Facebook account, their Facebook Graph API user fields are mapped to the Backendless user properties. A single mapping references a Facebook user field and the name of a Backendless property. The mapping is a required as it dictates which Facebook properties must be used when creating a corresponding Backendless user account. Once the user is authenticated, Backendless obtains the field values from the Facebook user graph object and populates the mapped properties in the BackendlessUser object. For the very first login, Backendless also creates the user in its internal system.

Permissions

The client application can request the permissions from the user to access additional user information or perform various actions. Requested permissions is a collection of string objects passed as an argument in the Backendless API call to login a Facebook user.

The Facebook permissions can be found at https://developers.facebook.com/docs/facebook-login/permissions/v2.2#reference.

Backendless Configuration

Backendless backend must be configured with Facebook's application App ID and secret key. See the "Social Settings" chapter of the user guide (the Manage section) for detailed instructions for configuring Backendless with Facebook.

Easy Facebook Login

Backendless client SDK and the server-side implementation follows the following process to support the easy login option:

1.The client application initiates the Facebook login sequence by calling a method from the Backendless SDK.
2.The invocation results in a UI dialog where the user enters their Facebook credentials and submits the form.
3.The form submission is sent to Facebook.
4.Upon successful login, Facebook executes a redirect to the Backendless servers.
5.Backendless receives the user information from Facebook and returns it back to the client.

The diagram below illustrates the process:

backendless-facebook-login

API

 


Description:

Perform Facebook user login. Backendless will obtain the Facebook fields which are available without access token - see the complete list of available fields. Backendless SDK uses the mobile Safari to show the Facebook login form.

-(void)easyLoginWithFacebookFieldsMapping:(NSDictionary<NSString*,NSString*> *)fieldsMapping 
                                           permissions:(NSArray<NSString*> *)permissions;
 
-(void)easyLoginWithFacebookFieldsMapping:(NSDictionary<NSString*,NSString*> *)fieldsMapping 
                                           permissions:(NSArray<NSString*> *)permissions 
                                           responder:(id<IResponder>)responder;

-(void)easyLoginWithFacebookFieldsMapping:(NSDictionary<NSString*,NSString*> *)fieldsMapping 
                                           permissions:(NSArray<NSString*> *)permissions 
                                           response:(void(^)(id))responseBlock 
                                           error:(void(^)(Fault *))errorBlock;
func easyLoginWithFacebookFieldsMapping(_ fieldsMapping: [String : String]!, 
                                        permissions  permissions: [String]!) -> Void
                                        
func easyLoginWithFacebookFieldsMapping(_ fieldsMapping: [String : String]!, 
                                        permissions  permissions: [String]!, 
                                        responder responder: IResponder! ) -> Void
                                        
func easyLoginWithFacebookFieldsMapping(_ fieldsMapping: [String : String]!, 
                                        permissions  permissions: [String]!, 
                                        response responseBlock: ((NSNumber!) -> Void)!, 
                                        error errorBlock: ((Fault!) -> Void)!) -> Void

where

fieldMappings- a mapping between the Facebook fields and Backendless user properties. Keys must be the names of the Facebook fields, values - the names of the Backendless properties. See the Property Mapping section for additional details.
permissions- a collection of the Facebook permissions/scopes which the application requests access to.

Requirements

There are several requirements for using the "Easy Facebook Login" option in an iOS application. Make sure to follow the instructions below:

1.Obtain your application ID and secret key.
2.Make sure to initialize the application using the initApp method as described in the Setup section.
3.Open the .plist file from the "Supporting Files" section of the XCode project and add a URL Scheme as shown below. Make sure the value of the URL scheme is backendless{APP_ID}, where {APP_ID} is the Application ID obtained in step 1. For example, if the Application ID is XXXX-YYYY-ZZZZ, the URL Scheme value must be backendlessXXXX-YYYY-ZZZZ.
backendless-url-scheme
4.Declare the following method in your AppDelegate class. The method is invoked when the Facebook login is successful and user identity is established:

-(BOOL)application:(UIApplication *)application 
                    openURL:(NSURL *)url 
                    sourceApplication:(NSString *)sourceApplication 
                    annotation:(id)annotation
{
    BackendlessUser *user = [backendless.userService handleOpenURL:url];
    if (user) {
        // apply your logic for the successful login. For example, switch the view
    }
    return YES;
}
func application(application: UIApplication, 
                 openURL url: NSURL, 
                 sourceApplication: String?, 
                 annotation: AnyObject) -> Bool {
        
        print("AppDelegate -> application:openURL: \(url.scheme)")
        
        let backendless = Backendless.sharedInstance()
        let user = backendless.userService.handleOpenURL(url)
        if user != nil {
            print("AppDelegate -> application:openURL: user = \(user)")
            
            // do something, call some ViewController method, for example
        }
        
        return true
    }
5.Use the easyLoginWithFacebookFieldsMapping method documented above to initiate the login sequence.

Example:

-(void)easyFacebookLogin {
           
           [backendless.userService
             easyLoginWithFacebookFieldsMapping:@{@"email":@"email"},
             permissions:@[@"email"]
             response:^(NSNumber * response) {
                 //response - NSNumber with bool Yes
                 NSLog(@"StartViewController -> login: (Facebook) result = %@", response);
             } error:^(Fault *fault) {
                 NSLog(@"StartViewController -> login: (FAULT) %@", fault.detail);
            }];
}
    func easyFacebookLogin() {
        
        backendless.userService.easyLoginWithFacebookFieldsMapping(
            ["email":"email"], permissions: ["email"],
            response: {(result : NSNumber!) -> () in
                print ("Result: \(result)")
            },
            error: { (fault : Fault!) -> () in
                print("Server reported an error: \(fault)")
        })
    }

 

Login With Facebook SDK

As the name suggests this option uses the Facebook SDK to handle the login to a Backendless application. The result of the operation is an instance of the BackendlessUser class which contains the property values initialized from the Facebook user account. Using the Facebook SDK with Backendless consists of the following steps:

Configure the environment with the Facebook SDK. Complete instructions are available at: https://developers.facebook.com/docs/ios/getting-started
Configure Backendless backend with the Facebook App ID/API Key.

 

API:

When using Facebook SDK  version 4.0 or above:

-(id)loginWithFacebookSDK:(FBSDKAccessToken *)accessToken 
                           fieldsMapping:(NSDictionary<NSString*,NSString*> *)fieldsMapping;

-(BackendlessUser *)loginWithFacebookSDK:(FBSDKAccessToken *)accessToken 
                                          fieldsMapping:(NSDictionary<NSString*,NSString*> *)fieldsMapping 
                                          error:(Fault **)fault;

-(void)loginWithFacebookSDK:(FBSDKAccessToken *)accessToken 
                             fieldsMapping:(NSDictionary<NSString*,NSString*> *)fieldsMapping 
                             responder:(id <IResponder>)responder;

-(void)loginWithFacebookSDK:(FBSDKAccessToken *)accessToken 
                             fieldsMapping:(NSDictionary<NSString*,NSString*> *)fieldsMapping 
                             response:(void(^)(BackendlessUser *))responseBlock 
                             error:(void(^)(Fault *))errorBlock;
func loginWithFacebookSDK(_ accessToken: FBSDKAccessToken, 
                          fieldsMapping fieldsMapping: [String : String]! ) -> AnyObject!

func loginWithFacebookSDK(_ accessToken: FBSDKAccessToken, 
                          fieldsMapping fieldsMapping: [String : String]!, 
                          error fault: AutoreleasingUnsafeMutablePointer<Fault?>) -> BackendlessUser!

func loginWithFacebookSDK(_ accessToken: FBSDKAccessToken, 
                          fieldsMapping fieldsMapping: [String : String]!, 
                          responder responder: IResponder! ) -> Void

func loginWithFacebookSDK(_ accessToken: FBSDKAccessToken, 
                          fieldsMapping fieldsMapping: [String : String]!, 
                          response responseBlock: ((BackendlessUser!) -> Void)!, 
                          error  errorBlock:((Fault!) -> Void)!) -> Void

where:

accessToken        - represents an immutable access token for using Facebook services.

fault                - an object which received fault information when server responds with an error.

fieldMapping- a mapping between the Facebook fields and Backendless user properties. Keys must be the names of the Facebook fields, values - the names of the Backendless properties. See the Property Mapping section for additional details.
responder- an object which receives either a return value or an error from the server. The return value from the server is BackendlessUser object. The class of the responder object must implement the IResponder protocol

When creating an application with uses the Facebook SDK, make sure to follow the steps below:

1.Add Facebook SDK to your project per the instructions from:
https://developers.facebook.com/docs/ios/getting-started
2.Make sure Info.plist looks as shown below:
info_plist.zoom50
3.Add the following code in AppDelegate.m/AppDelegate.swift:

#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import "Backendless.h"
static NSString *APP_ID = @"YOUR-APP-ID-GOES-HERE";
static NSString *SECRET_KEY = @"YOUR-IOS-SECRET-KEY-GOES-HERE";
static NSString *VERSION_NUM = @"v1";

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application 
   didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   [backendless initApp:APP_ID secret:SECRET_KEY version:VERSION_NUM];
   @try {
        [backendless initAppFault];
   }
   @catch (Fault *fault) {
        NSLog(@"didFinishLaunchingWithOptions: %@", fault);
   }
   return [[FBSDKApplicationDelegate sharedInstance] application:application 
            didFinishLaunchingWithOptions:launchOptions];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [FBSDKAppEvents activateApp];
}

- (BOOL)application:(UIApplication *)application 
                     openURL:(NSURL *)url 
                     sourceApplication:(NSString *)sourceApplication 
                     annotation:(id)annotation {
   BOOL result = [[FBSDKApplicationDelegate sharedInstance] 
                   application:application 
                   openURL:url 
                   sourceApplication:sourceApplication 
                   annotation:annotation];
   FBSDKAccessToken *token = [FBSDKAccessToken currentAccessToken];
   @try {
      BackendlessUser *user = [backendless.userService loginWithFacebookSDK:token fieldsMapping:nil];
      NSLog(@"USER: %@", user);
   }
   @catch (Fault *fault) {
      NSLog(@"openURL: %@", fault);
   }
   return result;
}
@end
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    let APP_ID = "YOUR-APP-ID-GOES-HERE"
    let SECRET_KEY = "YOUR-IOS-SECRET-KEY-GOES-HERE"
    let VERSION_NUM = "v1"
    
    var backendless = Backendless.sharedInstance()
    
    func application(application: UIApplication, 
                     openURL url: NSURL, 
                     sourceApplication: String?, 
                     annotation: AnyObject) -> Bool {
        let result = FBSDKApplicationDelegate.sharedInstance().application(application, 
                            openURL: url, 
                            sourceApplication: sourceApplication, 
                            annotation: annotation)
        if result {
            
            let token = FBSDKAccessToken.currentAccessToken()
            let fieldsMapping = [
                "id" : "facebookId",
                "name" : "name",
                "birthday": "birthday",
                "first_name": "fb_first_name",
                "last_name" : "fb_last_name",
                "gender": "gender",
                "email": "email"
            ]
            
            backendless.userService.loginWithFacebookSDK(
                token,
                fieldsMapping: fieldsMapping,
                response: { (user: BackendlessUser!) -> Void in
                    print("user: \(user)")
               },
                error: { (fault: Fault!) -> Void in
                    print("Server reported an error: \(fault)")
            })
        }
        
        return result
    }

    func application(application: UIApplication, 
                     didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        backendless.initApp(APP_ID, secret:SECRET_KEY, version:VERSION_NUM)

        return FBSDKApplicationDelegate.sharedInstance().application(application, 
                       didFinishLaunchingWithOptions: launchOptions)
    }
}
4.Add the following code in ViewController.m/ViewController.swift:

#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
    loginButton.center = self.view.center;
    [self.view addSubview:loginButton];
}
@end
class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let loginButton = FBSDKLoginButton()
        loginButton.center = self.view.center
        self.view.addSubview(loginButton)
    }
}

Please let us know how we can improve the documentation by leaving a comment. All technical questions should be posted to the Backendless Support forum. We do not respond to the technical questions on the documentation pages.: