TheQ
TheQ

Reputation: 2009

How to add facebook user to aws cognito? - android

I am a bit confused. I was able to set up Facebook login button using facebook sdk. Next, I wanted to add the user into cognito, but the guide told me to do this:

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

I did that, and I don't see the user incognito. I'm confused, what does "federated authentication" mean? What I'm trying to accomplish is:

1.User registers via Facebook 2.Once the facebook login is success, I want to add that user into cognition.

This is my current code:

    private void setFacebookButton()
    {
        Log.d("MY_FACEBOOK","setting up callbackManager");
        callbackManager = CallbackManager.Factory.create();
        loginButton.setReadPermissions("user_friends");
        loginButton.setReadPermissions("public_profile");
        loginButton.setReadPermissions("email");
        loginButton.setReadPermissions("user_birthday");
        // If using in a fragment
        loginButton.setFragment(this);
        // Callback registration

        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        Log.d("MY_FACEBOOK","login success!");
                        Map<String, String> logins = new HashMap<String, String>();
                        logins.put("graph.facebook.com", AccessToken.getCurrentAccessToken().getToken());
                        SetLoginsAsyncTask loginsAsyncTask = new SetLoginsAsyncTask(logins);
                        loginsAsyncTask.execute();
                    }

                    @Override
                    public void onCancel() {
                        // App code
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        // App code
                    }
                });
    }

    public class SetLoginsAsyncTask extends AsyncTask<Void,Void,Void>
    {
        private Map<String,String> logins = new HashMap<>();
        public SetLoginsAsyncTask(Map<String,String> logins)
        {
            this.logins = logins;
        }
        @Override
        protected Void doInBackground(Void... params)
        {
            myCognito.getCredentialsProvider().setLogins(logins);
            myCognito.getCredentialsProvider().refresh();
            String testing = myCognito.getCredentialsProvider().getCredentials().getSessionToken();
            if(testing != null)
            {
                Log.d("MY_FACEBOOK","testing is " + testing);
            }
            else
            {
                Log.d("MY_FACEBOOK","testing is null");
            }
            return null;
        }
        @Override
        public void onPostExecute(Void var)
        {

        }
    }

So I'm a bit confused, what the next steps are after the facebook login button returns you the user and their firstName, LastName, email, etc. I want to add that user into Cognito and be confirmed.

Hope someone can clarify with proper steps and code.

Cheers

Upvotes: 1

Views: 1318

Answers (1)

Ruby
Ruby

Reputation: 1441

It depends on the AWS SDK for Android version you are using. AWS Auth SDK for Android was introduced in 2.6.0.

  1. Add the following snippet to AndroidManifest.xml
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" 

    <!-- . . . -->

    <activity
        android:name="com.facebook.FacebookActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="@string/fb_login_protocol_scheme" />
        </intent-filter>
    </activity>

    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id" />
  1. Import the following dependencies in gradle.
        compile 'com.android.support:support-v4:24.+'
        compile ('com.amazonaws:aws-android-sdk-auth-facebook:2.6.+@aar') { transitive = true; }
        // Dependencies for the SDK Sign-in prompt UI library
        compile 'com.android.support:appcompat-v7:24.+'
        compile ('com.amazonaws:aws-android-sdk-auth-ui:2.6.+@aar') { transitive = true; }
  1. Do the following imports:
    import com.amazonaws.mobile.config.AWSConfiguration; <br/>
    import com.amazonaws.mobile.auth.core.IdentityManager; <br/>
    import com.amazonaws.mobile.auth.facebook.FacebookSignInProvider;                                                                             ; <br/>
    import com.amazonaws.mobile.auth.core.IdentityManager;<br/>
    import com.amazonaws.mobile.auth.ui.AuthUIConfiguration;<br/>
    import com.amazonaws.mobile.auth.ui.SignInActivity;<br/>
    import com.amazonaws.mobile.auth.facebook.FacebookButton;<br/>
    import com.amazonaws.mobile.auth.core.DefaultSignInResultHandler;<br/>                                                                            
  1. Add your FB App ID in strings.xml
<string name="facebook_app_id">1231231231232123123</string>
<string name="fb_login_protocol_scheme">fb1231231231232123123</string>
  1. Register Facebook SignInProvider in Application.java
    private void initializeApplication() {

            AWSConfiguration awsConfiguration = new AWSConfiguration(getApplicationContext());

           // If IdentityManager is not created, create it
           if (IdentityManager.getDefaultIdentityManager() == null) {
                   IdentityManager identityManager =
                        new IdentityManager(getApplicationContext(), awsConfiguration);
                   IdentityManager.setDefaultIdentityManager(identityManager);
               }

               // Add Facebook as Identity Provider.
               IdentityManager.getDefaultIdentityManager().addSignInProvider(
                    FacebookSignInProvider.class);
               FacebookSignInProvider.setPermissions("public_profile");

             // . . .

            }
  1. Manage the SignInUI
    import com.amazonaws.mobile.auth.core.DefaultSignInResultHandler;<br/>
    import com.amazonaws.mobile.auth.core.IdentityManager;<br/>
    import com.amazonaws.mobile.auth.core.IdentityProvider;<br/>
    import com.amazonaws.mobile.auth.core.StartupAuthErrorDetails;<br/>
    import com.amazonaws.mobile.auth.core.StartupAuthResult;<br/>
    import com.amazonaws.mobile.auth.core.StartupAuthResultHandler;<br/>
    import com.amazonaws.mobile.auth.core.signin.AuthException;<br/>
    import com.amazonaws.mobile.auth.ui.AuthUIConfiguration;<br/>
    import com.amazonaws.mobile.auth.ui.SignInActivity;<br/>

    @Override<br/>
    protected void onCreate(Bundle savedInstanceState) {<br/>
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        final IdentityManager identityManager = 
                IdentityManager.getDefaultIdentityManager();

        identityManager.doStartupAuth(this,
            new StartupAuthResultHandler() {
                @Override
                public void onComplete(final StartupAuthResult authResults) {
                    if (authResults.isUserSignedIn()) {
                        final IdentityProvider provider = 
                                identityManager.getCurrentIdentityProvider();

                        // If the user was  signed in previously with a provider,
                        // indicate that to them with a toast.
                        Toast.makeText(
                                SplashActivity.this, String.format("Signed in with %s",
                                provider.getDisplayName()), Toast.LENGTH_LONG).show();
                        callingActivity.startActivity(new Intent(SplashActivity.this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));<br/>
                        callingActivity.finish();
                        return;

                    } else {
                        // Either the user has never signed in with a provider before 
                        // or refresh failed with a previously signed in provider.

                        // Optionally, you may want to check if refresh 
                        // failed for the previously signed in provider.

                        final StartupAuthErrorDetails errors = 
                                authResults.getErrorDetails();

                         if (errors.didErrorOccurRefreshingProvider()) {
                            final AuthException providerAuthException = 
                                errors.getProviderRefreshException();

                            // Credentials for previously signed-in provider could not be refreshed
                            // The identity provider name is available here using: 
                            //     providerAuthException.getProvider().getDisplayName()

                        }


                        doSignIn(IdentityManager.getDefaultIdentityManager());
                        return;
                    }


                }
            }, 2000);
    }

    private void doSignIn(final IdentityManager identityManager) {

        identityManager.setUpToAuthenticate(
                SplashActivity.this, new DefaultSignInResultHandler() {

                    @Override
                    public void onSuccess(Activity activity, IdentityProvider identityProvider) {
                        if (identityProvider != null) {

                            // Sign-in succeeded
                            // The identity provider name is available here using: 
                            //     identityProvider.getDisplayName()

                        }

                        // On Success of SignIn go to your startup activity
                        activity.startActivity(new Intent(activity, MainActivity.class)
                                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                    }

                    @Override
                    public boolean onCancel(Activity activity) {

                        // Return false to prevent the user from dismissing 
                        // the sign in screen by pressing back button.
                        // Return true to allow this.

                        return false;
                    }
                });

        AuthUIConfiguration config =
                new AuthUIConfiguration.Builder()
                                       .signInButton(FacebookButton.class)
                                       // .signInButton(GoogleButton.class)
                                       // .userPools(true)
                                       .build();

        Context context = SplashActivity.this;
        SignInActivity.startSignInActivity(context, config);
        SplashActivity.this.finish();
    }

Upvotes: 3

Related Questions