ZOFTINO.COM android and web dev tutorials

Registration and Login with Facebook Account User Id & Password

In your mobile app or website, there could be certain features or functionalities which are available to registered users only. In that case, you need to provide capability for users to do registration or sign up for those features.

The most common way to provide sign up functionality is to let users create an account within the app or website with new user id and password. But most users don’t like to remember one more user id and password. So to eliminate the need for users to create new user id and password, to use restricted features of your app or website, you can implement account registration functionality using Facebook login credentials.

Facebook provides SDK for IOS and Andriod apps for Facebook login. For websites, Facebook provides Javascript SDK.

In this article I am going to show how to implement Facebook login for websites using Facebook Graph API from server side. For this, we rely on RestFB client framework to talk to Facebook Graph API.

First you need to create Facebook app for your website. Below are the rest of the steps involved in manual Facebook login flow.

  1. Note your Facebook app id.
  2. Create Facebook app secret.
  3. On user clicking Facebook-Login button in your website login page, your server side code redirects the user to below Facebook url with required parameters.

    https://www.facebook.com/dialog/oauth?client_id=appid&redirect_uri=your-website-url&scope=email&state=

    Here client id is your facebook app id and redirect-uri points to your website where login is handled. Scope parameter is used to specify permission. Email permission gives access to just primary email address.

    State parameter is used to send unique string which is used to prevent cross site request forgery. You need to store state in server side session for later verification.
  4. Above redirect takes user to Facebook login page where user logs in with Facebook account user id and password.
  5. On successful authentication, user will be redirected to the url passed in redirect_uri parameter.
  6. Facebook adds code parameter to redirect-uri before it redirects.
  7. In the action code where above redirect_uir is handled, you need to verify state code received from redirect request parameter to match it with state code from your server side session. This step is necessary to prevent cross site request forgery.
  8. Using http client, execute below http get request passing required parameters. Client_id parameter is your facebook app id. Client secret is your app secret. Code is the code received in above redirect request.

    https://graph.facebook.com/v2.3/oauth/access_token?client_id=yourappid&redirect_uri=&client_secret=yourfacebookappsecret&code=

  9. You will get Json response for above request. You need to retrieve access_token parameter from the Json response.
  10. Using facebook app secret and above mentioned access token, call “me” graph api to get user details like emails address and name.
  11. If user logins first time, create account using above user details in your db to identify user in your website.
  12. Make sure you implement logout properly. You need to not only invalidate session but also call Facebook logout. Below is the Facebook logout url you need to redirect to, passing access token which you received while logging in.

    https://www.facebook.com/logout.php?next=yourwebsiteafterlogouturl&access_token=

Below is Java code with all steps required to perform Facebook login.


	@RequestMapping(value = "/account/fbsignin", method = RequestMethod.GET)
	public String faceBookLogin(HttpServletRequest request, ModelMap model){
		String fbsigninUrl = "https://www.facebook.com/dialog/oauth?client_id=appid&redirect_uri=yourdomain%2Faccount%2Ffbsignin&scope=email&state=";
		String fbIdConfirmUrl = "https://graph.facebook.com/v2.3/oauth/access_token?client_id=appid&redirect_uri=yourdomain%2Faccount%2Ffbsignin&client_secret=appsecret&code=";
		String fbappsec = "appsecret";

		
		//check to see if user already logged in
		if(!("anonymousUser".equals(SecurityContextHolder.getContext().getAuthentication().getName()))){
			return "redirect:/myaccount.htm";
		}
		String fbcode =  request.getParameter("code");
		String state =  request.getParameter("state");

		if(StringUtils.isEmpty(state) || StringUtils.isEmpty(fbcode)){
			String statekey = RandomStringUtils.randomAlphanumeric(40);
			request.getSession().setAttribute("fbstate", statekey);
			return "redirect:"+fbsigninUrl+statekey;				
		}else{
			String statekey = (String)request.getSession().getAttribute("fbstate");
			if(!state.equals(statekey)){
				model.addAttribute("errormsg","Login error");	
				return "loginpage";
			}
			FacebookClient fbclient = new DefaultFacebookClient(Version.VERSION_2_3);

			try {
				Response fbrs = fbclient.getWebRequestor().executeGet(fbIdConfirmUrl+fbcode);
				if(fbrs.getStatusCode() != 200){
					model.addAttribute("errormsg","Login error");	
					return "loginpage";
				}
				JsonObject json = new JsonObject(fbrs.getBody().toString());

				request.getSession().setAttribute("fbacesstoken", json.getString("access_token"));
				
				FacebookClient facebookClient = new DefaultFacebookClient(json.getString("access_token"), fbappsec, Version.VERSION_2_3);
				User user = facebookClient.fetchObject("me", User.class);

							
				processSocialLogin(user.getId(),user.getEmail(), user.getFirstName()+" "+user.getLastName(),
						                      "FB",json.getString("access_token"), request);

			} catch (Exception e) {
				model.addAttribute("errormsglg","Login error");	
				return "loginpage";
			}

		}			
		return "redirect:/myaccount.htm";
	}