Boot

Spring Boot Social Login Example

Welcome readers, in this tutorial, we will create a simple spring boot application that authenticates a user via Facebook credentials and displays his/her profile information using Spring Social.

1. Introduction

  • Spring Boot is a module that provides rapid application development feature to the spring framework including auto-configuration, standalone-code, and production-ready code
  • It creates applications that are packaged as jar and are directly started using embedded servlet container (such as Tomcat, Jetty or Undertow). Thus, no need to deploy the war files
  • It simplifies the maven configuration by providing the starter template and helps to resolve the dependency conflicts. It automatically identifies the required dependencies and imports them in the application
  • It helps in removing the boilerplate code, extra annotations, and xml configurations
  • It provides a powerful batch processing and manages the rest endpoints
  • It provides an efficient jpa-starter library to effectively connect the application with the relational databases

1.1 Introduction to Spring Social

  • Invoke API on behalf of users and simplify the OAuth 2.0 calls
  • Enables the application to establish a connection with SaaS (Software-as-a-Service) providers such as Twitter and Facebook

Now, open the eclipse ide and let’s see how to implement this tutorial in spring boot.

2. Spring Boot Social Login Example

Here is a systematic guide for implementing this tutorial.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MongoDB, and Maven.

2.2 Project Structure

In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.

Spring Boot Social Login - Application
Fig. 1: Application Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring Boot Social Login - Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.

Spring Boot Social Login - Project Details
Fig. 3: Project Details

Select the Maven Web App archetype from the list of options and click next.

Spring Boot Social Login - Archetype Selection
Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Spring Boot Social Login - Archetype Parameters
Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<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.springboot.sociologin</groupId>
	<artifactId>Springbootsociologintutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

Let’s start building the application!

3. Creating a Spring Boot application

Below are the steps involved in developing the application. But before starting we are assuming that developers have created new application id through the Facebook developer page.

Spring Boot Social Login - New Application Id
Fig. 6: Creating a New Application Id

3.1 Maven Dependencies

Here, we specify the dependencies for the Spring Boot and Spring Social. Maven will automatically resolve the other dependencies. The updated file will have the following code.

pom.xml

<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.springboot.sociologin</groupId>
	<artifactId>Springbootsociologintutorial</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>

	<name>Springboot Socio Login Tutorial</name>
	<url>http://maven.apache.org</url>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.4.RELEASE</version>
	</parent>

	<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>
	
	<build>
		<finalName>Springbootsociologintutorial</finalName>
	</build>
</project>

3.2 Application Properties

Create a new properties file at the location: Springbootsociologintutorial/src/main/resources/ and add the following code to it.

application.properties

# Application configuration.
server.port=8102

# Mvc configuration.
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

3.3 Java Classes

Let’s write all the java classes involved in this application.

3.3.1 Implementation/Main class

Add the following code the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication annotation and the static main method.

Myapplication.java

package com.springboot.socio.facebook;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Main implementation class which serves two purposes in a spring boot application: Configuration and bootstrapping.
 * @author yatin-batra
 */
@SpringBootApplication
public class Myapplication {

	public static void main(String[] args) {
		SpringApplication.run(Myapplication.class, args);
	}
}

3.3.2 Controller class

Add the following code to the controller class designed to handle the incoming requests. The class is annotated with the @Controller annotation. Here we will use the FacebookConnectionFactory object for making the OAuth2.0 call to Facebook to fetch the authorization code and the access token.

Facebookctrl.java

package com.springboot.socio.facebook.ctrl;

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.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * Class to show the index page, validate facebook credentials, and display the user details.
 * @author yatin-batra
 */
@Controller
public class Facebookctrl {

	// Creates a facebook connection using the given application id and secret key.
	private FacebookConnectionFactory factory = new FacebookConnectionFactory("<!-- Your application id -->", "<!-- Your secret key -->");

	// Index page.
	@GetMapping(value= "/")
	public ModelAndView index() {
		return new ModelAndView("welcome");
	}

	// Redirection uri.
	@GetMapping(value = "/useapp")
	public String redirect() {
		// Creates the OAuth2.0 flow and performs the oauth handshake on behalf of the user.
		OAuth2Operations operations= factory.getOAuthOperations();

		// Builds the OAuth2.0 authorize url and the scope parameters.
		OAuth2Parameters params= new OAuth2Parameters();
		params.setRedirectUri("http://localhost:8102/forwardLogin");
		params.setScope("email, public_profile");

		// Url to redirect the user for authentication via OAuth2.0 authorization code grant.
		String authUrl = operations.buildAuthenticateUrl(params);
		System.out.println("Generated url is= " + authUrl);
		return "redirect:" + authUrl;
	}

	// Welcome page.
	@GetMapping(value = "/forwardLogin")
	public ModelAndView prodducer(@RequestParam("code") String authorizationCode) {
		// Creates the OAuth2.0 flow and performs the oauth handshake on behalf of the user.
		OAuth2Operations operations= factory.getOAuthOperations();

		// OAuth2.0 access token.
		// "exchangeForAccess()" method exchanges the authorization code for an access grant.
		AccessGrant accessToken= operations.exchangeForAccess(authorizationCode, "http://localhost:8102/forwardLogin", null);

		Connection<Facebook> connection= factory.createConnection(accessToken);

		// Getting the connection that the current user has with facebook.
		Facebook facebook= connection.getApi();
		// Fetching the details from the facebook.
		String[] fields = { "id", "name", "email", "about", "birthday"};
		User userProfile= facebook.fetchObject("me", User.class, fields);

		ModelAndView model = new ModelAndView("details");
		model.addObject("user", userProfile);
		return model;
	}
}

4. Run the Application

As we are ready with all the changes, let us compile the spring boot project and run the application as a java project. Right click on the Myapplication.java class, Run As -> Java Application.

Spring Boot Social Login - Run
Fig. 7: Run the Application

Developers can debug the example and see what happens after every step. Enjoy!

5. Project Demo

Go to localhost:8102 and the index page will be displayed.

Spring Boot Social Login - Index Page
Fig. 8: Index Page

Click on the button and it’ll ask the user to enter the facebook credentials. If the credential validation is successful we’ll get the profile details of the user.

Spring Boot Social Login - Facebook Profile
Fig. 9: Facebook Profile Details

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

In this section, developers learned how to implement Facebook authentication using Spring Social in a simple spring boot application. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of implementing Spring Social with Spring Boot.

Download
You can download the full source code of this example here: Spring Boot Social Login Example

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Johan
Johan
4 years ago

Why you said in tools that you are using mongoDB?

Back to top button