Core Java

Using Social Login Authentication in Spring Boot with OAuth2

Social login is a mechanism that allows users to sign into an application using their existing credentials from social networking services like Facebook, GitHub and Google. This method is increasingly popular due to its simplicity and convenience for users. This article will explore how to authenticate using social login in a Spring Boot application using spring-boot-starter-oauth2-client.

1. Register with Social Login Providers

In this section, we will go through the steps to register with Facebook and Google as social login providers and obtain the client ID and secret.

1.1 Facebook

Go to the Facebook Developer Portal: Facebook Developers.

Create a new app: Navigate to “My Apps” and click “Create App“.

Facebook social login authentication start page

Choose “Authenticate and request data from users with Facebook Login” and provide the required details.

Configure the app: After creating the app, navigate to “App Settings” -> “Basic” to find your App ID and App Secret. Scroll down to “App Secret” and click on “Show

Navigate to “Use Cases” -> “Customize“.

Configure the OAuth settings by going to “Settings” and setting the Valid OAuth Redirect URIs to http://localhost:8080/login/oauth2/code/facebook. This URI will be used by Facebook to redirect users back to the application after a successful login.

1.2 google

  • Go to the Google Developer Console: Google Cloud Console
  • Create a new project:
    • Click on the project dropdown and select “New Project“.
  • Configure OAuth consent screen:
    • Navigate to “OAuth consent screen” and configure your application details.
  • Create OAuth 2.0 credentials:
    • Go to “Credentials” -> “Create Credentials” -> “OAuth 2.0 Client IDs“.
    • Set the application type to “Web application” and configure the redirect URIs. For development, use http://localhost:8080/login/oauth2/code/google.

2. Set Up Spring Boot Project

Create a new Spring Boot project using Spring Initializr or your IDE and include dependencies for spring-boot-starter-oauth2-client and spring-boot-starter-web.

pom.xml

<dependencies>
    <dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
</dependencies>

3. Configure Spring Security

Once you have obtained the necessary credentials from your social login providers, the next step is to configure Spring Security to enable social login in your application. This involves setting up the application.properties file and creating the necessary security configurations.

3.1 Configure application.properties

First, we need to add the OAuth 2.0 client registration details to the application.properties file. This configuration includes client IDs and client secrets for the social login providers.

application.properties

spring.security.oauth2.client.registration.google.client-id=YOUR_GOOGLE_CLIENT_ID
spring.security.oauth2.client.registration.google.client-secret=YOUR_GOOGLE_CLIENT_SECRET

spring.security.oauth2.client.registration.facebook.client-id=YOUR_FACEBOOK_APP_ID
spring.security.oauth2.client.registration.facebook.client-secret=YOUR_FACEBOOK_APP_SECRET

3.2 Configure Security Configuration

Next, create a security configuration class to set up OAuth 2.0 login using Spring Security.

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorizeRequests
                        -> authorizeRequests
                        .requestMatchers("/index").permitAll()
                        .anyRequest().authenticated()
                ).oauth2Login(Customizer.withDefaults());

        return http.build();
    }
}

This SecurityConfig class configures the Spring Security for the application. It specifies that:

  • The /index URL is publicly accessible without authentication.
  • Any other URL requires the user to be authenticated.
  • Additionally, it enables OAuth2 login with default settings, allowing users to authenticate via OAuth2 providers.

4. Controller for Handling Login

Create a simple controller to handle the login and secure pages.

HomeController.java

@RestController
public class HomeController {

    @GetMapping("/index")
    public String getLoginPage() {
        return "This is a public page.";
    }

    @GetMapping("/secure")
    public String getSecurePage() {
        return "This is a secured page.";
    }
}

The above HomeController class is a simple Spring REST controller that defines two endpoints:

  • /index: This endpoint is publicly accessible.
  • /secure: According to the security configuration provided in the previous steps, accessing this endpoint would require the user to be authenticated. When you attempt to access the /secure endpoint, the application will display an auto-generated login page featuring two client options.

The login page will look like this:

Spring Authorization: Social Login Authentication with OAuth2 Login Page
Spring Authorization: Social Login Authentication with OAuth2 Login Page

Clicking on the Facebook or Google login links will redirect users to the respective sign-in pages provided by these platforms. After successfully logging in, users will be redirected back to the /secure endpoint URL.

5. Conclusion

In this article, we explored how to implement social login authentication using Spring Boot with OAuth2. We started by registering our application with Facebook and Google to obtain the necessary credentials. Next, we configured the Spring Boot application using application.properties to set up OAuth2 client registrations for these social login providers. We then created a security configuration class to handle the authentication process and set up a controller to manage the login and secured pages.

6. Download the Source Code

This was an article on spring authorization server social login authentication.

Download
You can download the full source code of this example here: spring authorization server social login authentication

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button