Facebook (identity pools)
Amazon Cognito identity pools integrate 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 IdP.
Set up Facebook
Register your application with Facebook before you authenticate Facebook users and interact with Facebook APIs.
The Facebook Developers portal
Setting up Facebook
-
At the Facebook Developers portal
, log in with your Facebook credentials. -
From the Apps menu, select Add a New App.
-
Select a platform and complete the quick start process.
Android
For more information about how to integrate Android apps with Facebook Login, see the
Facebook
Getting Started Guide
iOS - Objective-C
For more information about how to integrate iOS Objective-C apps with Facebook Login,
see the Facebook
Getting Started Guide
iOS - Swift
For more information about how to integrate iOS Swift apps with Facebook Login, see
the Facebook
Getting Started Guide
JavaScript
For more information about how to integrate JavaScript web apps with Facebook Login,
see the Facebook Getting Started Guide
Unity
For more information about how to integrate Unity apps with Facebook Login, see the
Facebook Getting Started
Guide
Xamarin
To add Facebook authentication, first follow the appropriate flow below to integrate the Facebook SDK into your application. Amazon Cognito identity pools use the Facebook access token to generate a unique user identifier that is associated with an Amazon Cognito identity.
Configure the external provider in the Amazon Cognito federated identities console
Use the following procedure to configure your external provider.
-
Choose Manage Identity Pools from the Amazon Cognito console home page
. -
Choose the name of the identity pool where you want to enable Facebook as an external provider. The Dashboard page for your identity pool appears.
-
In the top-right corner of the Dashboard page, choose Edit identity pool. The Edit identity pool page appears.
-
Scroll down and choose Authentication providers to expand the section.
-
Choose the Facebook tab.
-
Choose Unlock.
-
Enter the Facebook App ID you obtained from Facebook, and then choose Save Changes.
Using Facebook
Android
To add Facebook authentication, first follow the Facebook guide
After you authenticate your user with the Facebook SDK, add the session token to the Amazon Cognito credentials provider.
Facebook SDK 4.0 or later:
Map<String, String> logins = new HashMap<String, String>(); logins.put("graph.facebook.com", AccessToken.getCurrentAccessToken().getToken()); credentialsProvider.setLogins(logins);
Facebook SDK before 4.0:
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 that matches this particular Facebook identity. If the user already exists, the API returns the existing identifier. Otherwise, the API returns a new identifier. The client SDK automatically caches identifiers on the local device.
After you set the logins map, make a call to refresh
or
get
to retrieve the AWS credentials.
iOS - Objective-C
To add Facebook authentication, first follow the Facebook guide
To provide the Facebook access token to Amazon Cognito, implement the AWSIdentityProviderManager
When you implement the logins
method, return a dictionary that contains
AWSIdentityProviderFacebook
. This dictionary acts as the key, and the
current access token from the authenticated Facebook user acts as the value, as shown in
the following code example.
- (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
iOS - Swift
To add Facebook authentication, first follow the Facebook guide
To provide the Facebook access token to Amazon Cognito, implement the AWSIdentityProviderManager
When you implement the logins
method, return a dictionary containing
AWSIdentityProviderFacebook
. This dictionary acts as the key, and the
current access token from the authenticated Facebook user acts as the value, as shown in
the following code example.
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
JavaScript
To add Facebook authentication, follow the Facebook Login for the Web
After you authenticate your user with the Facebook SDK, add the session token to the Amazon Cognito credentials provider.
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 Amazon 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.
After you set the logins map, make a call to refresh
or
get
to get the credentials. For a code example, see "Use Case 17,
Integrating User Pools with Cognito Identity," in the JavaScript README file
Unity
To add Facebook authentication, first follow the Facebook guideFB
object to generate a unique user identifier that is associated with an
Amazon Cognito identity.
After you authenticate your user with the Facebook SDK, add the session token to the Amazon Cognito credentials provider:
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); }
Before you use FB.AccessToken
, call FB.Login()
and make sure
FB.IsLoggedIn
is true.
Xamarin
Xamarin for Android:
public void InitializeFacebook() { FacebookSdk.SdkInitialize(this.ApplicationContext); callbackManager = CallbackManagerFactory.Create(); LoginManager.Instance.RegisterCallback(callbackManager, new FacebookCallback < LoginResult > () { HandleSuccess = loginResult = > { var accessToken = loginResult.AccessToken; credentials.AddLogin("graph.facebook.com", accessToken.Token); //open new activity }, HandleCancel = () = > { //throw error message }, HandleError = loginError = > { //throw error message } }); LoginManager.Instance.LogInWithReadPermissions(this, new List < string > { "public_profile" }); }
Xamarin for iOS:
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 } }); }