Integrating Facebook Login

Integrating Facebook Login

Facebook login is considered as one of the most preferable way for authenticating users. This approach is also very convenient for the users as Facebook has very deep reach among users. This post will illustrate as to how to integrate Facebook login as a way of authenticating users. We will be using Javascript SDK provided by Facebook.

window.fbAsyncInit = function() {
    FB.init({
      appId      : '<yourAppId>',
      xfbml      : true,
      version    : 'v2.7'
    });

  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));

First of all place above piece of code in your head section, it will load the Javascript SDK asynchronously. Now the SDK has been loaded and initialized and we are good to pump in our logic into it.

What Facebook does is it will open a page and then user will enter their Facebook credentials. Now we need to make sure that the Facebook login page should not be blocked by the browser, so do this event on a button. Also make sure that you have a valid appId, visit Facebook developers site for it.

https://developers.facebook.com

<a href="javascript:loginFB()">Connect with Facebook</a>

Now lets define our loginFB() function.

function loginFB(){
var accessToken;
   	FB.login(function(response){
   		if (response.authResponse) {
     		console.log('Welcome!  Fetching your information.... ');
     		accessToken=response.authResponse.accessToken;
     		alert(response.authResponse.accessToken);
     		getFBInfo();
     		//window.location="${pageContext.request.contextPath}"+"/fconnect.html?accessToken="+accessToken;
    	} else {
     		console.log('User cancelled login or did not fully authorize.');
    	}
   	}, {scope: "public_profile,email,publish_actions",return_scopes: true});
   }

function getFBInfo(){
   	FB.api("/me","GET",{fields:"first_name,last_name,name,id,email"},function(response){
   		alert(response.email);
   	});
   }

With FB.login() function a page is opened and user enters their Facebook credentials and user needs to authorize the Facebook APP. If the user gets authenticated successfully the we get accessToken. Now this accessToken will be used for further communicating with Facebook, as this token is a proof that the user is a valid Facebook user. After successful authentication we executed getFBInfo() that calls FB.api() graph API to fetch user’s information. Whatever information is required you need to mention it against fields property.

Or, you can pass this token to server, or say a servlet that will use REST Facebook library in order to use the accessToken for gaining user’s information.

com.restfb.FacebookClient facebookClient=facebookClient = new com.restfb.DefaultFacebookClient(accessToken);
com.restfb.types.User user = facebookClient.fetchObject("me", com.restfb.types.User.class);

Don’t forget to configure rest FB JAR in your project. Oh, you also need to configure your appId against above client. After this you will have the information about user in user object.

After doing this you can check the Facebook email Id with your user’s Login email Id and see if it matches.

You can also check if the user is already logged into Facebook via new tab.

FB.getLoginStatus(function(response){
var accessToken;
    	if(response.status==='connected'){
    		alert('We are connected');
    		accessToken=response.authResponse.accessToken;
    		alert(response.authResponse.accessToken);
    		getFBInfo();
    	}else if(response.status==='not_authorized'){
    		alert('LoggedIn but not authorized');
    	}else{
    		alert('You are not logged into Facebook');
    	}
    });
  };