What are Social Logins?
Many mobile apps require a user to create an account or to sign up for a service in order to use them. From a user’s point of view, this can be somewhat troublesome or annoying, and it’s not always the best user experience.
So how can you overcome this when building your app? To give users a seamless experience, you can give them the ability to sign in to your app with just a single tap of a button, using one of their social networking accounts, e.g., Facebook or Twitter.
In this tutorial, you’ll learn how to integrate a user’s Facebook and Twitter accounts into your Android app to allow them to log in and also share posts from your app into their social networking account.
Almost every major social network provides an API to allow application developers to authenticate users using their systems. In this article we will focus on the four major social login providers: Google, Facebook, Twitter and Instagram.
Single-sign-on, OAuth2 and social logins
Related to social login is the concept of single-sign-on. Single-sign-on allows users visiting different domains to remain logged-in using the same credentials. One can easily picture how social logins can help in doing this: by authenticating using a third-party service, different domains can share user information.
Many social login providers opt to provide a standardized way to authorize access to their login services through the OAuth2 standard. OAuth2 specifies a series of operations that clients can perform against an authorization server. It is the authorization server's job to issue tokens (pieces of information) that can later be used by these clients to access protected resources. In the case of social logins, protected resources are user profiles and other data associated with them. Although the use of OAuth2 for certain tasks has been criticized by various parties, it remains the most common standard for social logins.
In the case of our four providers, all of them provide OAuth-based APIs. Twitter in particular relies on OAuth 1.0a, while other providers use OAuth 2.0. For the purposes of this post however, we will prefer the official native Android libraries of each provider (except for Instagram, for which there is no official Android lib).
Requirements and Setup
For our examples we will use the latest version of Android Studio, the official Android IDE. Go to the site, and follow the install instructions for your platform.
All our examples should work on recent versions of Android. We picked Android 5.0 as base, but older versions should work as well.
Create our sample application
In Android Studio, go to File
-> New Project
and follow the wizard. When asked about the main screen, select an Empty Activity. Call this activity LoginActivity
.
Setup the emulator
After the wizard is done, it should be possible to run the example using the emulator. If you haven't done so, setup an emulator supporting Google Services (this is required). Go to Tools
->Android
-> AVD Manager
-> Create Virtual Device
. Create a device supporting Google Play. Pick a device that can be accelerated by your platform (x86) and enable GPU acceleration (Use Host GPU
). This will ensure the best possible experience for our tests.
It is now time to run the sample app using the emulator. If everything goes well you should see something like this:
Step-by-step implementations
Now we are all set to start integrating our social logins into our app. Let's dive in:
Facebook provides a native Android SDK to use its services, let's see how to get it integrated:
1. SETUP THE REPOSITORY AND DEPENDENCIES
On Android Studio's sidebar look for the build.gradle
file associated to the project and add the following line:
Then go to the build.grade
file for your app module and add the following dependency:
2. TELL FACEBOOK ABOUT YOUR APP
Facebook's backend needs to know about your application. Go tohttps://developers.facebook.com/apps and click Add a New App
, then follow the wizard:
If you are familiar with Android development, you know applications are digitally signed. If not, what you need to know is that there two types of signatures: release and development signatures. Release signatures are used when you publish to the Google Play Store. Development signatures are used otherwise. In this case we are using our development signature. To get it, run the following code in your terminal (the default keystore password is android
):
Input the generated hash code in the form and click next.
You can safely ignore what follows in the Facebook app wizard. Now go to https://developers.facebook.com/apps/ and copy your app id to the clipboard.
3. SETUP THE SDK IN YOUR ANDROID PROJECT
Add your Facebook App ID to your string resources file (string.xml
) as facebook_app_id
. Then edit your AndroidManifest.xml
file to add: - The necessary permissions (uses-permission
). - The Facebook app id as metadata (meta-data
tag). - The Facebook activity.
4. ADD THE FACEBOOK LOGIN BUTTON
The Facebook SDK for Android comes with a convenient button that can be added easily to our activities. Open activity_login.xml
with the text editor. Add a LinearLayout
element and put the Facebook button in it:
5. BIND EVERYTHING WITH CODE
First, do the necessary SDK initialization in your app's main activityonCreate
method:
Setup the callback for button (inside onCreate
might be a good choice as well):
Lastly, the proper callback must be bound in the onActivityResult
callback:
That's it! In the handleSignInResult
method of your activity you can do as you please (usually show another activity or do some operation with the information from the current user).
As expected, Google provides a native Android SDK to handle logins. Let's see how we can add it to our existing app.
1. MAKE SURE THE GOOGLE PLAY SERVICES SDK IS AVAILABLE
In Android Studio, go to Tools
-> Android
-> SDK Manager
-> SDK Tools
. In the Extras section make sure Google Play Services is available and enabled.
2. SETUP THE REPOSITORY AND DEPENDENCIES
Open the build.grade
file for your project and add the Play Services classpath:
Now open the build.grade
file for your app module and the Google Services plugin and compile-time dependency:
3. TELL GOOGLE ABOUT YOUR APP
Go to the Google Developer Console and add your app. It will first ask for the usual stuff: your app's name and the Android package name for it. After that you will be presented with several Google services which you can enable. Choose Google Sign-In
:
As happened for Facebook sign-in, Google too requires the certificate fingerprint. To get the development fingerprint run the following command (password android
):
After Google Sign-In is enabled, a new button at the end of the page will appear: Generate Configuration Files
. Click it and download the configuration file. Browse to your Android project folder and find the app
subfolder. Place the google-services.json
file there:
4. ADD THE GOOGLE SIGN-IN BUTTON
Open the layout file for your login activity (activity_login.xml
) and place the button in a container:
5. GLUE IT ALL TOGETHER WITH CODE
Bind the button to your callback method:
Handle the callback by presenting the Google Sign-In activity:
Lastly, handle the result from the activity:
You can now pass the login details from the result
object to your custom handleSignInResult
method. To get the user details, useresult.getSignInAccount()
. That's it!
Twitter also provides a native SDK for Android. Let's see how we can integrate it.
1. SETUP THE REPOSITORY AND DEPENDENCIES
Twitter provides an Android Studio plugin named Fabric. Fabric is also the name of the libraries Twitter provides developers to help in the integration of their APIs. The Fabric plugin comes with a set of wizards to help in the integration of its features. For the purposes of this post we will do all steps manually (no Fabric wizards).
Open the build.gradle
file for your project and add the following lines:
Then in the app module build.gradle
file add the following:
2. TELL TWITTER ABOUT YOUR APP
Go to https://apps.twitter.com/ and create a new app. Set the callback URL to any domain under your control but do not leave it blank. This will be ignored by the Twitter SDK for Android, but will cause trouble if left blank.
After the app is created, you will be presented with the settings screen. First set your permissions to read-only (nothing more is required for signing-in), then go to the Keys and Access Tokens
screen and take note of both the Consumer Key
and the Consumer Secret
.
You will also need to create an account at fabric.io. Once you have done this, login and go to organizations. Click on your organization and then click on API Key
. Put this key in yourAndroidManifest.xml
file:
3. ADD THE TWITTER SIGN-IN BUTTON
Open activity_login.xml
and add the Twitter sign-in button:
4. GLUE EVERYTHING WITH CODE
In your login activity class add the following code to initialize Twitter's SDK:
The keys in this block of code are the ones you got in step 2. Note the comment in the block of code. The secret key for your Twitter app should never be made public (the key above was revoked before publishing). This means that embedding the key in code like we have done in this case is a security issue you should consider. The recommended way of handling this is on a best-effort basis. If you are keen on security issues this should immediately trigger an alarm in your head. Yes, Twitter's own API forces us to use insecure practices. One way to mitigate this issue is to use DexGuard to obfuscate strings. This is, however, imperfect and will not prevent a dedicated black-hat from getting your secret keys. The only safe way of handling this limitation is by not using the Android native SDK and reverting to the OAuth HTTP-based API. This way the secret key can be stored in a server of your choice. Twitter is aware of this limitation and remains silent in the way of potential fixes. Consider this carefully when picking the native Twitter for Android SDK for your apps.
Now we can add a handler for Twitter's button:
You can get the user details by calling result.data.getUserName()
.
Finally, it is necessary to handle the response sent from the Twitter sign-in activity:
That's all there is to it. Remember in this case to consider the potential security issues brought by keeping the secret key for Twitter's API in your code.
In contrast with the other social login services in this post, Instagram provides no native library for Android (or any other platform), so we will focus on how to integrate it in our sample using an HTTP API and Android intents.
1. TELL INSTAGRAM ABOUT YOUR APP
Go to https://www.instagram.com/developer/clients/register/ and register a new app. For the redirect URL
we will use a special URL that can be captured by an Android intent. For our example we usedsociallogin://redirect
(yes, a custom schema is possible and recommended).
In the security
tab enable implicit OAuth by unchecking the box that reads "Disable Implicit OAuth". Implicit OAuth is simpler for the purposes of our example. Read the Instagram authentication docs to find out if the explicit authentication flow is appropriate for your use case.
2. ADD AN INTENT FILTER TO CATCH THE REDIRECT
Once the application is authenticated (or not) by Instagram, a redirect will be performed to the URL set in step 1. We will setup our application to catch those URLs so that it gets launched when the browser is redirected them. Open AndroidManifest.xml
and add the following attribute to the login activity:
3. ADD A STANDARD ANDROID BUTTON TO THE LAYOUT
Open activity_login.xml
and add the following:
4. ADD THE CODE
Now add the code to do all the magic. First, setup a handler for the button:
And here is signInWithInstagram
:
You can get your client id fromhttps://www.instagram.com/developer/clients/manage/.
To handle the return from the activity, look for the callback URI:
You can call this function in the onCreate
or onStart
callbacks for the activity. With the access token it is then possible to query for information regarding the user by queryinghttps://api.instagram.com/v1/users/self/?access_token=ACCESS-TOKEN
. That is all there is to it!
Get the full example code for all providers.
Aside: Don't Repeat Yourself, use Auth0
If you've read this far you probably realized supporting several social logins providers is somewhat cumbersome. Using our Lock libraryfor Android makes this a breeze. Integrating it is as simple as integrating any of the solutions mentioned above, with the added benefit that you pick which social login providers are supported from the settings dashboard. Yup, that's it: do this integration once and get as many social login providers as you want with a few clicks! Let's see how it is done.
1. SIGN UP
Go to https://auth0.com/ and sign-up.
2. CREATE AN EMPTY ANDROID PROJECT
Click on File
-> New
-> New Project
and follow the steps. A project like the one we created for our sample above will do just fine.
3. TELL AUTH0 ABOUT YOUR APP
Open the dashboard and click on New App/API
.
Now go to Connections
-> Social
and enable as many social providers as you like. Follow the usual steps to get the application ids or consumer keys. For testing, you can leave the fields blank and use Auth0's internal test keys. Don't forget to enable these connections in your new app (Apps/APIs
-> <APP NAME>
-> Connections
).
4. SETUP LOCK'S DEPENDENCIES
Open your app module build.gradle
file and add the following:
5. ADD LOCK'S ACTIVITY TO YOUR MANIFEST FILE
Open AndroidManifest.xml
and add the following:
Now add the client id and Auth0 domain to your strings.xml
file. To get these details go to the Auth0 dashboard and select your app, then pick settings
.
Internet permissions are necessary:
6. GLUE EVERYTHING TOGETHER WITH CODE
Put the following code in your main activity or global application object:
The receiver
object can be implemented as follows:
And to show the Auth0 Lock activity put this in any place where you can trigger this code:
That's it! Now when Lock activity is shown all your picked social login providers will be available. You can add or remove additional connections from the Auth0 dashboard. No more special cases.
Get the full code.
keyword:
how to make calculator in android,how to,how to create android app,step to step tutorial of hacking android mobile,android login facebook tutorial,steps connecting bmw to app,how to make android apps,social logins,android,how to setup android,android (operating system),how to make free android,social engineering