Navigation

Facebook Authentication

Overview

The Facebook authentication provider allows users to log in with their existing Facebook account through a companion Facebook application. When a user logs in, Facebook provides Stitch with an OAuth 2.0 access token for the user. Stitch uses the token to identify the user and access approved data from the Facebook API on their behalf. For more information on Facebook Login, see Facebook Login for Apps.

Configuration

You can enable and configure the Facebook authentication provider from the Stitch UI by selecting Facebook from the Users > Providers page.

You can enable and configure the Facebook authentication provider with stitch-cli by importing an application directory that contains a configuration file for the provider.

The configuration file must be named oauth2-facebook.json and stored in the /auth_providers directory. Configuration files for the Facebook authentication provider have the following form:

/auth_providers/oauth2-facebook.json
{
  "name": "oauth2-facebook",
  "type": "oauth2-facebook",
  "disabled": <boolean>,
  "config": {
    "clientId": <string>
  },
  "metadata_fields": [<document>, ...],
  "redirect_uris": [<string>, ...],
  "domain_restrictions": [<string>, ...]
}

The Facebook authentication provider has the following configuration options:

Field Description

Client ID

config.clientId

Required. The App ID of the Facebook app.

See Set Up a Facebook App for information about setting up your Facebook app and finding the App ID.

Client Secret

Defined in secrets.json

Required. The App Secret of the Facebook app.

See Set Up a Facebook App for information about setting up your Facebook app and finding the App Secret.

Note

Client Secret is not defined in the provider configuration file for import/export. Instead, it’s defined in secrets.json using the following form:

"auth_providers": {
  "oauth2-facebook": {
    "clientSecret": "<secret>"
  }
}

Metadata Fields

metadata_fields

Optional. A list of fields describing the authenticated user that your application will request from the Facebook Graph API.

All metadata fields are omitted by default and can be required on a field-by-field basis. Users must explicitly grant your app permission to access each required field. If a metadata field is required and exists for a particular user, it will be included in their user object.

To require a metadata field from an import/export configuration file, add an entry for the field to the metadata_fields array. Each entry should be a document of the following form:

{ name: "<metadata field name>", required: "<boolean>" }

Redirect URIs

redirect_uris

Required for web applications. A list of allowed redirect URIs.

Once a user completes the authentication process on Facebook, Stitch redirects them back to either a specified redirect URI or, if no redirect URI is specified, the URL that they initiated the authentication request from. Stitch will only redirect a user to a URI that exactly matches an entry in this list, including the protocol and any trailing slashes.

Domain Restrictions

domain_restrictions

Optional. A list of approved domains for user accounts.

If specified, the provider checks the domain of a user’s primary email address on Facebook and only allows them to authenticate if the domain matches an entry in this list.

For example, if example1.com and example2.com are listed, a Facebook user with a primary email of joe.schmoe@example1.com would be allowed to log in, while a user with a primary email of joe.schmoe@example3.com would not be allowed to log in.

Note

If you’ve specified any domain restrictions, you must also require the email address field in the Metadata Fields setting.

Usage

Set Up a Facebook App

The Facebook authentication provider requires a Facebook app to manage authentication and user permissions. The following steps walk through creating the app, setting up Facebook Login, and configuring the provider to connect with the app.

1

Create a Facebook App

Follow Facebook’s official guide to create a new Facebook app.

2

Enable Facebook Login

From the app’s Dasboard view, find the Facebook Login card and click Set Up. You should see a list of quickstart guides for each platform. Follow the guide for your platform to enable Facebook Login.

Note

Stitch web applications do not require you to install the Facebook SDK to use the Facebook authentication provider. If you are incorporating Facebook Login into a web application you can skip any steps in the quickstart related to setting up the Facebook SDK for Javascript.

3

Add Stitch as a Valid OAuth Redirect URI

When a user completes the login flow for your Facebook app they need to be redirected back to Stitch. Facebook Login will only allow users to redirect to a pre-approved list of URIs.

From the Facebook Login > Settings page, add the following Stitch authentication callback URL to the list of Valid OAuth Redirect URIs:

https://stitch.mongodb.com/api/client/v2.0/auth/callback
4

Configure the Facebook Authentication Provider

To connect your Facebook app to Stitch, find your Facebook app’s App ID and App Secret values on the Settings > Basic page and add them to your authentication provider configuration.

Authenticate a User

To begin authenticating a user with the Facebook authentication provider, call StitchAuth.loginWithRedirect() with an instance of FacebookRedirectCredential:

if (!client.auth.isLoggedIn) {
   const credential = new FacebookRedirectCredential();
   Stitch.defaultAppClient.auth.loginWithRedirect(credential);
}

In web apps, Facebook authentication redirects users to a page hosted on a Facebook domain. Once a user enters their credentials on this page, Facebook will confirm or deny their identity and, if successfully authenticated, ask them for permission to share their data with the application. Facebook will then redirect to Stitch, where the user’s access token is saved and the user is redirected back to the redirect URI. The redirect URI must appear in the list of Redirect URIs specified in the provider configuration, otherwise the login process will not complete successfully.

When control is returned to your application, you must handle the Facebook redirect by calling handleRedirectResult(), as follows:

if (client.auth.hasRedirectResult()) {
    client.auth.handleRedirectResult().then(user => {
        console.log(user);
    });
}

Specify a Redirect (Optional)

By default, Stitch redirects users to the URL of the page from which they initiated the login request. To specify a redirect URI, include it as a parameter to the FacebookRedirectCredential constructor:

const credential = new FacebookRedirectCredential("<URL>");
Stitch.defaultAppClient.auth.loginWithRedirect(credential);

Note

The redirect URI is automatically stripped of any fragment identifiers.

For example, if the initial redirect URL is https://example.com/dashboard/#login, the user will be redirected to https://example.com/dashboard/.

Dependency

You must install the Facebook SDK for Android to use the Facebook authentiction provider in an Android application.

In Android applications, Facebook authentication is handled by either the LoginManager class or the LoginButton helper class. See the Facebook Login Getting Started Guide for more information.

Once a user initiates Facebook login, they are redirected to a login form on a Facebook domain. Facebook will confirm or deny their identity and ask them for permission to share their data with your application.

When a user has successfully authenticated, the Facebook SDK returns a LoginResult object which is passed to the login callback. The LoginResult object contains an AccessToken object for the authenticated user. In the onSuccess callback handler, instantiate a FacebookCredential with the access token string and pass the resulting credential as the argument to StitchAppClient.loginWithCredential().

Note

Ensure that you configure the Facebook Login SDK to request access permissions for each metadata field configured in the authentication provider. See Ask for Permissions for details on how to do this. A list of available permissions can be found here.

// Login Button onClick Handler
public void onClick(final View ignored) {
  _callbackManager = CallbackManager.Factory.create();
  LoginManager.getInstance().registerCallback(_callbackManager,
    new FacebookCallback<LoginResult>() {
      @Override
      public void onSuccess(LoginResult loginResult) {
        final FacebookCredential fbCredential =
          new FacebookCredential(loginResult.getAccessToken().getToken());

        Stitch.getDefaultAppClient().getAuth().loginWithCredential(fbCredential).addOnCompleteListener(
          new OnCompleteListener<StitchUser>() {
            @Override
            public void onComplete(@NonNull final Task<StitchUser> task) {
              if (task.isSuccessful()) {
                // Do something here
              } else {
                Log.e(TAG, "Error logging in with Facebook", task.getException());
              }
            }
        } );
    } }
  );
  LoginManager.getInstance().logInWithReadPermissions(
    MainActivity.this,
    Arrays.asList("public_profile")
  );
}

Dependency

You must install the Facebook SDK for Swift to use the Facebook authentiction provider in an iOS application.

In iOS applications, Facebook authentication is handled by either the LoginManager class or the LoginButton helper class. See the Facebook Login Getting Started Guide for more information.

Once a user initiates Facebook login, they are redirected to a login form on a Facebook domain. Facebook will confirm or deny their identity and ask them for permission to share their data with your application.

When a user has successfully authenticated, the Facebook SDK returns a LoginResult object which you should pass to a login handler in the app delegate. The LoginResult object contains an AccessToken for the authenticated user. In the login handler, instantiate a FacebookCredential with the access token and pass it as the argument to StitchAuth.login(withCredential:_:).

Note

Ensure that you configure the Facebook Login SDK to request access permissions for each metadata field configured in the authentication provider. See Ask for Permissions for details on how to do this. A list of available permissions can be found here.

func loginButtonDidCompleteLogin(_ loginButton: LoginButton, result: LoginResult) {
  switch result {
  case .success(_, _, let token):
    let fbCredential = FacebookCredential.init(withAuthCode: token.authenticationToken)
    Stitch.defaultAppClient!.auth.login(withCredential: fbCredential) { result in
      switch result {
      case .success:
        MongoDBManager.shared.provider = StitchProviderType.facebook
        self.delegate?.authenticationViewControllerDidLogin()
      case .failure(let error):
        print("failed logging in Stitch with Facebook. error: \(error)")
        LoginManager().logOut()
        self.show(show: true, errorMessage: error.localizedDescription)
      }
    }
  case .failed(let error):
     print("error received when logging in with Facebook: \(error.localizedDescription)")
     self.show(show: true, errorMessage: error.localizedDescription)
  default:
     break
  }
}