Menu
Amazon Cognito
Developer Guide (Version Last Updated: 07/28/2016)

Facebook

Amazon Cognito integrates with Facebook to provide federated authentication for your mobile application users. This section explains how to register and set up your application with Facebook as an identity provider.

Set Up Facebook

You need to register your application with Facebook before you can start authenticating Facebook users and interacting with Facebook APIs.

The Facebook Developers portal takes you through the process of setting up your application. If you haven't gone through that process yet, you'll need to do so before you can integrate Facebook in your Amazon Cognito Identity Pool:

To set up Facebook

  1. At the Facebook Developers portal, log in with your Facebook credentials.

  2. From the Apps menu, select Add a New App.

  3. Select a platform and complete the quick start process.

Android

The Facebook Getting Started Guide provides additional information on integrating with Facebook Login.

iOS - Objective-C

The Facebook Getting Started Guide provides additional information about integrating with Facebook Login.

iOS - Swift

The Facebook Getting Started Guide provides additional information about integrating with Facebook Login.

JavaScript

The Facebook Getting Started Guide provides additional information about integrating with Facebook Login.

Unity

The Facebook Getting Started Guide provides additional information about integrating with Facebook Login.

Xamarin

To provide Facebook authentication, first follow the appropriate flow below to include and set up the Facebook SDK in your application. Amazon Cognito uses the Facebook access token to generate a unique user identifier that is associated to a Cognito Identity.

Configure the External Provider in the Amazon Cognito Console

From the Amazon Cognito Console home page:

  1. Choose Manage Federated Identities.

  2. Choose the name of the identity pool for which you want to enable Facebook as an external provider. The Dashboard page for your identity pool appears.

  3. In the top-right corner of the Dashboard page, choose Edit identity pool. The Edit identity pool page appears.

  4. Scroll down and choose Authentication providers to expand it.

  5. Choose the Facebook tab.

  6. Choose Unlock.

  7. Enter the Facebook App ID you obtained from Facebook, and then choose Save Changes.

Using Facebook

Android

To provide Facebook authentication, first follow the Facebook guide to include their SDK in your application. Then add a "Login with Facebook" button to your Android user interface. The Facebook SDK uses a session object to track its state. Amazon Cognito uses the access token from this session object to authenticate the user, generate the unique identifier, and, if needed, grant the user access to other AWS resources.

Once you have authenticated your user with the Facebook SDK, add the session token to the Amazon Cognito credentials provider.

Facebook SDK 4.0 or later:

Copy
Map<String, String> logins = new HashMap<String, String>(); logins.put("graph.facebook.com", AccessToken.getCurrentAccessToken().getToken()); credentialsProvider.setLogins(logins);

Facebook SDK before 4.0:

Copy
Map<String, String> logins = new HashMap<String, String>(); logins.put("graph.facebook.com", Session.getActiveSession().getAccessToken()); credentialsProvider.setLogins(logins);

The Facebook login process initializes a singleton session in its SDK. The Facebook session object contains an OAuth token that Amazon Cognito uses to generate AWS credentials for your authenticated end user. Amazon Cognito also uses the token to check against your user database for the existence of a user matching this particular Facebook identity. If the user already exists, the API returns the existing identifier. Otherwise a new identifier is returned. Identifiers are automatically cached by the client SDK on the local device.

Note

After setting the logins map, you'll need to make a call to refresh or get to actually get the AWS credentials.

iOS - Objective-C

To add Facebook authentication, first follow the Facebook guide to integrate the Facebook SDK into your application. Then add a Login with Facebook button to your user interface. The Facebook SDK uses a session object to track its state. Amazon Cognito uses the access token from this session object to authenticate the user and bind them to a unique Amazon Cognito identity.

To provide the Facebook access token to Amazon Cognito, implement the AWSIdentityProviderManager protocol.

In the implementation of the logins method, return a dictionary containing AWSIdentityProviderFacebook as the key and the current access token from the authenticated Facebook user as the value, as shown in the following code example.

Copy
- (AWSTask<NSDictionary<NSString *, NSString *> *> *)logins { FBSDKAccessToken* fbToken = [FBSDKAccessToken currentAccessToken]; if(fbToken){ NSString *token = fbToken.tokenString; return [AWSTask taskWithResult: @{ AWSIdentityProviderFacebook : token }]; }else{ return [AWSTask taskWithError:[NSError errorWithDomain:@"Facebook Login" code:-1 userInfo:@{@"error":@"No current Facebook access token"}]]; } }

When you instantiate the AWSCognitoCredentialsProvider, pass the class that implements AWSIdentityProviderManager as the value of identityProviderManager in the constructor. For more information, go to the AWSCognitoCredentialsProvider reference page and choose initWithRegionType:identityPoolId:identityProviderManager.

iOS - Swift

To add Facebook authentication, first follow the Facebook guide to integrate the Facebook SDK into your application. Then add a Login with Facebook button to your user interface. The Facebook SDK uses a session object to track its state. Amazon Cognito uses the access token from this session object to authenticate the user and bind them to a unique Amazon Cognito identity.

To provide the Facebook access token to Amazon Cognito, implement the AWSIdentityProviderManager protocol.

In the implementation of the logins method, return a dictionary containing AWSIdentityProviderFacebook as the key and the current access token from the authenticated Facebook user as the value, as shown in the following code example.

Copy
class FacebookProvider: NSObject, AWSIdentityProviderManager { func logins() -> AWSTask<NSDictionary> { if let token = AccessToken.current?.authenticationToken { return AWSTask(result: [AWSIdentityProviderFacebook:token]) } return AWSTask(error:NSError(domain: "Facebook Login", code: -1 , userInfo: ["Facebook" : "No current Facebook access token"])) } }

When you instantiate the AWSCognitoCredentialsProvider, pass the class that implements AWSIdentityProviderManager as the value of identityProviderManager in the constructor. For more information, go to the AWSCognitoCredentialsProvider reference page and choose initWithRegionType:identityPoolId:identityProviderManager.

JavaScript

To provide Facebook authentication, follow the Facebook Login for the Web to add the "Login with Facebook" button on your website. The Facebook SDK uses a session object to track its state. Amazon Cognito uses the access token from this session object to authenticate the user, generate the unique identifier, and, if needed, grant the user access to other AWS resources.

Once you have authenticated your user with the Facebook SDK, add the session token to the Amazon Cognito credentials provider.

Copy
FB.login(function (response) { // Check if the user logged in successfully. if (response.authResponse) { console.log('You are now logged in.'); // Add the Facebook access token to the Cognito credentials login map. AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'IDENTITY_POOL_ID', Logins: { 'graph.facebook.com': response.authResponse.accessToken } }); // Obtain AWS credentials AWS.config.credentials.get(function(){ // Access AWS resources here. }); } else { console.log('There was a problem logging you in.'); } });

The Facebook SDK obtains an OAuth token that Amazon Cognito uses to generate AWS credentials for your authenticated end user. Amazon Cognito also uses the token to check against your user database for the existence of a user matching this particular Facebook identity. If the user already exists, the API returns the existing identifier. Otherwise a new identifier is returned. Identifiers are automatically cached by the client SDK on the local device.

Note

After setting the logins map, you need to make a call to refresh or get to get the AWS credentials. For a code example, see "Use Case 17, Integrating User Pools with Cognito Identity," in the JavaScript README file.

Unity

To provide Facebook authentication, first follow the Facebook guide to include and set up their SDK in your application. Amazon Cognito uses the Facebook access token from the 'FB' object to generate a unique user identifier that is associated to a Cognito Identity.

Once you have authenticated your user with the Facebook SDK, add the session token to the Amazon Cognito credentials provider:

Copy
void Start() { FB.Init(delegate() { if (FB.IsLoggedIn) { //User already logged in from a previous session AddFacebookTokenToCognito(); } else { FB.Login ("email", FacebookLoginCallback); } }); } void FacebookLoginCallback(FBResult result) { if (FB.IsLoggedIn) { AddFacebookTokenToCognito(); } else { Debug.Log("FB Login error"); } } void AddFacebookTokenToCognito() { credentials.AddLogin ("graph.facebook.com", AccessToken.CurrentAccessToken.TokenString); }

You should make sure to call FB.Login() and that FB.IsLoggedIn is true before using FB.AccessToken.

Xamarin

Xamarin for Android:

Copy
public void InitializeFacebook() { FacebookSdk.SdkInitialize(this.ApplicationContext); callbackManager = CallbackManagerFactory.Create(); LoginManager.Instance.RegisterCallback(callbackManager, new FacebookCallback &lt; LoginResult &gt; () { HandleSuccess = loginResult = &gt; { var accessToken = loginResult.AccessToken; credentials.AddLogin("graph.facebook.com", accessToken.Token); //open new activity }, HandleCancel = () = &gt; { //throw error message }, HandleError = loginError = &gt; { //throw error message } }); LoginManager.Instance.LogInWithReadPermissions(this, new List &lt; string &gt; { "public_profile" }); }

Xamarin for iOS:

Copy
public void InitializeFacebook() { LoginManager login = new LoginManager(); login.LogInWithReadPermissions(readPermissions.ToArray(), delegate(LoginManagerLoginResult result, NSError error) { if (error != null) { //throw error message } else if (result.IsCancelled) { //throw error message } else { var accessToken = loginResult.AccessToken; credentials.AddLogin("graph.facebook.com", accessToken.Token); //open new view controller } }); }