Search Tutorials


Facebook Authentication Using Spring Boot + Spring Social Simple Example| JavaInUse

Facebook Authentication Using Spring Boot + Spring Social Simple Example

In this example we will be creating a simple application that uses Facebook credentials to authenticate the user and get his basic details using Spring Social. The aim of this chapter is to learn the basics of Spring Social. In the next chapter we will be implementing a full fledged SSO login using Facebook, Google and Twitter login.
The user authorization for access to our application using Facebook is done using OAuth2 Authorization Code Grant Type.
In a previous post we had seen the working of OAuth2 Authorization Code Grant Type.
In the example we had implemented the authorization server and resource server. So when ever the client wished to fetch some data from the resource server he will first need to get a valid token from the authorization server.
Many real world applications like Quora, StackOverflow make use of authorization and resource servers of existing social organizations like google and Facebook for authenticating a user.

Spring Boot Security - Implementing OAuth2

Spring Boot Security - Introduction to OAuth Spring Boot OAuth2 Part 1 - Getting The Authorization Code Spring Boot OAuth2 Part 2 - Getting The Access Token And Using it to fetch data. Spring Boot + OAuth 2 Client Credentials Grant - Hello World Example. Spring Boot + OAuth 2 Password Grant - Hello World Example. Facebook Authentication Using Spring Boot + Spring Social Simple Example.
Consider the use case of Quora. Go to Quora.com.
If you are a new user you need to signup. You can signup using google or facebook account. When doing so you are authorizing Google or Facebook to allow quora to access you profile info with Quora. This authorizing is done using OAuth2 Authorization Code Grant. Here you have in no way shared your credentials with Quora.

boot-39_1
In the above example of Quora, we have 3 actors-
  • Resource Owner - This is the user who wants to sign up using Quora.
  • Client Application - This will be Quora
  • Resource Server - This will be Gmail or Facebook.
  • Authorization Server - The resource server hosts the protected user accounts, and the authorization server verifies the identity of the user then issues access tokens to the application.
The client application must first register with the authorization server associated with the resource server. This is usually a one-time task. Once registered, the registration remains valid, unless the client application registration is revoked. At registration the client application is assigned a client ID and a client secret (password) by the authorization server. The client ID and secret is unique to the client application on that authorization server.
For example if we click on Continue with Google, we get the following screen. Here we can see Quora client id.
boot-39_2
Quora got this client id and a secret key when it registered with Google.
The actual authorization process that takes place between Quora and Google using OAuth is as follows-
boot-39_3
In this example we will be creating a simple application that uses Facebook credentials to authenticate the user and get his basic details using Spring Social. The aim of this chapter is to learn the basics of Spring Social. In the next chapter we will be implementing a full fledged SSO login using Facebook, Google and Twitter login.

What is Spring Social

The Spring Social project enables your applications to establish Connections with Software-as-a-Service (SaaS) Providers such as Facebook and Twitter to invoke APIs on behalf of Users.
Spring social provides a wrapper over the API's exposed by the social media sites. Spring social hides the complexity of calling the Social Media sites using OAuth and simplify these calls.
You can get more information about Spring Social on their home page.




Lets Begin-

  • Create a Facebook developer account and get the client id and the client secret

    Go to Facebook developer page
    Facebook Developer Home Page
    Login using your facebook credentials
    Facebook Developer Login Page
    Create a new Application
    Facebook Developer New Application

    Facebook Developer JavaInUse Application

Go to the basic setting. Here we will get the app id and the app secret which will be our client id and client secret.
Facebook Developer Basic settings
  • Create an application for using the client id and client key

    The maven project will be as follows-
    Social Maven Project
    Define the pom.xml as follows- Add the spring-social-facebook dependency.
    	<?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    
    	<groupId>com.javainuse</groupId>
    	<artifactId>spring-boot-social</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<name>spring-boot-social</name>
    	<description>Demo project for Spring Boot Social</description>
    
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>1.4.1.RELEASE</version>
    		<relativePath /> <!-- lookup parent from repository -->
    	</parent>
    
    	<properties>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    		<java.version>1.8</java.version>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    
    		<dependency>
    			<groupId>org.apache.tomcat.embed</groupId>
    			<artifactId>tomcat-embed-jasper</artifactId>
    		</dependency>
    
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>jstl</artifactId>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework.social</groupId>
    			<artifactId>spring-social-facebook</artifactId>
    			<version>2.0.3.RELEASE</version>
    		</dependency>
    	</dependencies>
    
    
    </project>
    	

    Facebook Social Flow
    Next we will be defining the Controller. In the controller using the FacebookConnectionFactory provided by the Spring Facebook Social we make OAuth call to Facebook to get the Auhtorization Code and the Access Token.
    	package com.javainuse.controllers;
    
    import org.springframework.social.connect.Connection;
    import org.springframework.social.facebook.api.Facebook;
    import org.springframework.social.facebook.api.User;
    import org.springframework.social.facebook.connect.FacebookConnectionFactory;
    import org.springframework.social.oauth2.AccessGrant;
    import org.springframework.social.oauth2.OAuth2Operations;
    import org.springframework.social.oauth2.OAuth2Parameters;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    
    @Controller
    public class SocialFacebookController {
    
    	private FacebookConnectionFactory factory = new FacebookConnectionFactory("643726556084467",
    			"c7c175dc6f35671d17b14app60250rgk");
    
    	@RequestMapping("/")
    	public ModelAndView firstPage() {
    		return new ModelAndView("welcome");
    	}
    
    	@GetMapping(value = "/useApplication")
    	public String producer() {
    
    		OAuth2Operations operations = factory.getOAuthOperations();
    		OAuth2Parameters params = new OAuth2Parameters();
    
    		params.setRedirectUri("http://localhost:8080/forwardLogin");
    		params.setScope("email,public_profile");
    
    		String url = operations.buildAuthenticateUrl(params);
    		System.out.println("The URL is" + url);
    		return "redirect:" + url;
    
    	}
    
    	@RequestMapping(value = "/forwardLogin")
    	public ModelAndView prodducer(@RequestParam("code") String authorizationCode) {
    		OAuth2Operations operations = factory.getOAuthOperations();
    		AccessGrant accessToken = operations.exchangeForAccess(authorizationCode, "http://localhost:8080/forwardLogin",
    				null);
    
    		Connection<Facebook> connection = factory.createConnection(accessToken);
    		Facebook facebook = connection.getApi();
    		String[] fields = { "id", "email", "first_name", "last_name" };
    		User userProfile = facebook.fetchObject("me", User.class, fields);
    		ModelAndView model = new ModelAndView("details");
    		model.addObject("user", userProfile);
    		return model;
    
    	}
    
    }
    	
    	
    Create the Spring Boot Main class-
    	package com.javainuse;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class SpringBootSocialApplication {
    
    	public static void main(String[] args) {
    		SpringApplication.run(SpringBootSocialApplication.class, args);
    	}
    }
    	
    	
    Create the welcome.jsp
    	<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    
    <div style="border: 1px solid #ccc; padding: 5px; margin-bottom: 20px;">
    
        <a href="/useApplication">Validate using Facebook</a> |  
    
    </div>
    	
    Create the details.jsp
    <h1>Your Facebook Email is - </h1>
    <h1>Your Facebook First Name is - </h1>
    <h1>Your Facebook Last Name is - </h1>
    	
  • Next start the Spring application by running it as a Java Application. Go to localhost:8080-
    Social Home Page
    Click on the link. It will ask for the log in using facebook.
    Social Output Page
    We get the Facebook user details.

    Download Source Code

    Download it -
    Spring Boot + Spring Social Hello World Example