Blog
navigate_next
Java
Spring Security 6 → OAuth 2.0(Social Login) with SpringBoot 3
Gaurav Sharma
May 6, 2024

In this article, I'll show you how to set up social logins like GitHub and Google using OAuth2.0 in your Spring Boot 3 application. We'll go through how easy it is to integrate this system, making managing logins a breeze.

What is OAuth 2.0?

OAuth 2.0, short for "Open Authorization version 2.0," is a standard protocol that allows third-party services to access user data securely without the user's password.

Let's simplify OAuth 2.0 with an everyday analogy:

Imagine you're at a coffee shop with a friend, and you want to buy a pastry, but you left your wallet in the car. Instead of going out to get it, your friend, who the barista knows and trusts, vouches for you. Based on your friend's word, the barista hands you a pastry. In this scenario, OAuth 2.0 is like your friend vouching for you. It's a way for someone who knows you (like Google or Facebook or any-other) to tell another service (a new app) that you're okay and can be trusted.

Understanding OAuth 2.0 :

Common Terms You'll Frequently Encounter:

  • Resource Owner: This is typically the user who owns the data or has the authority to grant access to it.
  • Client: This is the application or service that wants to access the user's data, but doesn't get direct access to credentials.
  • Resource Server: This server actually holds the user's data. It responds to requests for this data, provided they come with the correct access token.
  • Authorization Server: This server is responsible for authenticating the user's identity and issuing access tokens to the client after the user grants permission.

How Does OAuth 2.0 Work?

<aside>💡 Note: Spring OAuth-client offers built-in support for social logins such as Google and GitHub, eliminating the need to set up your own authorization server. Much of the backend work required for these integrations is managed automatically by Spring OAuth-client.

</aside>

Here’s how the OAuth 2.0 process works, using the example of booking a car online through your Google account to make you understand better:

  1. Initiating Login: You go to a car rental website and see an option to log in with your Google account.
  2. Application Requests Permission: When you click on "Log in with Google," the car rental website (the Client) asks Google (the Authorization Server) for permission to access basic information from your account.
  3. Granting Permission: As the user and the owner of the Google account (the Resource Owner), you agree to grant the car rental website access to your name and email address.
  4. Application Requests Access: Google issues a temporary code to the car rental website once you give your consent.
  5. Access Granted by Google: The car rental website exchanges the temporary code for a permanent access token at Google.
  6. Application Retrieves Data: With this access token, the car rental website can now retrieve your name and email from Google to set up or confirm your reservation, all without needing to know your Google password.

Behind the Scenes:

Why Use OAuth 2.0?

  • Security: You don’t have to give your password to every app or website; Google (or another provider) just tells the app you're legit.
  • Control: You can control what information you share—maybe just your email address and not your whole Google life.
  • Convenience: It's super easy to use one account to sign into many different services.

Using OAuth 2.0 in Spring Boot 3

If you're building a Spring Boot 3 app, adding OAuth 2.0 means you're setting up a way for your app to talk to trusted providers like Google.

Spring Boot handles most of the technical stuff, making sure that when a user clicks "Log in with Google," everything goes smoothly, from asking Google if the user is legit to letting the user into your app.

Objective:

We aim to develop a single REST endpoint in our Spring Boot application that can be accessed only after authenticating via Google or GitHub login.

The project uses dependencies for OAuth2 client integration and web application development, including <span class="pink">spring-boot-starter-oauth2-client</span> and <span class="pink">spring-boot-starter-web</span>.

Note: Our primary goal is to secure the API and enable access through social login. Therefore, we won't delve deeply into the internal mechanics of OAuth2 with Spring Boot.

We are using a maven project for our spring boot application.

HelloController.java


package com.unlogged;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Unlogged: Open-source tool for Java devs to instantly mock DB/APIs, auto-generate unit tests from API traffic, monitor method performance, and save/replay method inputs & outputs. Integrates with CI for code coverage. Install to boost your Java DevOps! ";
    }
}

Explanation: This class is part of a web application that manages incoming requests. When you access the <span class="pink">/api/hello</span> URL, it displays a message about "Unlogged," a tool designed for Java developers. You can only view this message if you are logged in using OAuth2, such as through social login options like Google or GitHub.

SecurityConfig.java


package com.unlogged;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity.authorizeHttpRequests
                        (auth -> auth.anyRequest().authenticated())
                .oauth2Login(Customizer.withDefaults())
                .build();
    }
}

Explanation: This class is crucial for integrating OAuth2 into your Spring Boot application. It configures web security so that:

  • <span class="pink">authorizeHttpRequests(auth -> auth.anyRequest().authenticated())</span>: This line ensures that any request to the server must be authenticated, meaning no one can access any part of your application without first logging in.
  • <span class="pink">.oauth2Login(Customizer.withDefaults())</span>: This sets up the default configuration for OAuth2 login. It tells Spring Security to handle login using OAuth2, which lets users authenticate using external providers like Google and GitHub.

To enable social login in our Spring Boot application, Spring offers built-in support through the oauth2-client. All we need to do is include this dependency in our pom.xml file.

💡 The oauth2-client dependency automatically includes Spring Security as a transitive dependency. This means when you add it to your project, it not only enables OAuth2 capabilities for logging in with services like Google or Facebook but also enhances your application’s security. Essentially, by adding just one dependency, you get both authentication support and robust security features seamlessly integrated into your springboot application.

Dependency for OAuth2 Client Integration in Spring Boot:


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

The final version of our pom.xml file will look like this:


<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.unlogged</groupId>
    <artifactId>SimpleOauth2Project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SimpleOauth2Project</name>
    <description>SimpleOauth2Project</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties


spring.application.name=SimpleOauth2Project

#GitHub Oauth2 credentials
spring.security.oauth2.client.registration.github.client-id=ec415f229e8f06f6ddb
spring.security.oauth2.client.registration.github.client-secret=53dc2b2125d356c652dfb83fbc0d209de4a9f60


#google Oauth2 credentials
spring.security.oauth2.client.registration.google.client-id=8741050757-9q8tgp7raiqbhv79pfiqktpnq1cmgd8.apps.googleusercontent.com
spring.security.oauth2.client.registration.google.client-secret=GOCSPX-uXkDADJlMzl_-4FBJ2q6PSdwGgj

Explanation:

These lines configure your application to use OAuth2 authentication with GitHub and Google.The "client-id" and "client-secret" are unique keys given by GitHub and Google when you register your application with them.These credentials are crucial for the authentication process, allowing your application to request and obtain permission to access user information securely from GitHub and Google, under the OAuth2 protocol.

Additional Key Terms:

The terms "Redirect URI" and "Callback URL" generally refer to the same concept in OAuth 2.0. Both describe the URL to which the user is sent back after authorizing with the external service.

💡 Redirect URI: This is the internet address where the app is sent back to after it has been given permission to access your data.

💡 Our application is configured to operate on port 8080. Please ensure you use the precise callback URL or redirect URI by adjusting the port your Spring Boot application uses to match this.

  • The Callback URL for GitHub is <span class="pink">http://localhost:8080/login/oauth2/code/github</span>, which is where GitHub redirects after authentication.
  • The Redirect URI for Google is <span class="pink">http://localhost:8080/login/oauth2/code/google</span>, the endpoint Google uses to return users after they have given permissions.
  • 302 status code is a redirection code

Guide on How to Retrieve Client ID and Secret Key from GitHub:

  1. Log In to GitHub: Sign into your GitHub account.
  2. Navigate to OAuth Apps: Go to Settings -> Developer settings -> OAuth Apps.
  3. Create New OAuth App: Click New OAuth App.
  4. Fill Application Details:
    • Application Name: Enter a name for your application.
    • Homepage URL: Provide the URL where your application is hosted.
    • Authorization callback URL: Specify where GitHub should redirect after user authorization.
  5. Register the Application: Click Register application.
  6. Retrieve Client ID and Secret:
    • Note down the Client ID shown on the application details page.
    • Click Generate a new client secret and copy the secret immediately.
  7. Secure and Use Credentials: Store the client secret securely and use both credentials in your application to integrate GitHub’s OAuth2 services.

A demo is provided for reference:

Guide on How to Retrieve Client ID and Secret Key from Google:

  1. Log in to Google Cloud Console: Access Google Cloud Console and sign into your Google account.
  2. Access API & Services: From the left sidebar, click on APIs & Services.
  3. Configure OAuth Consent Screen:
    • Navigate to OAuth consent screen tab.
    • Fill in the form with your application’s details. You can leave most fields as they are set by default, just make sure to enter your app's name and email address.
  4. Create Credentials:
    • Go to the Credentials tab.
    • Click Create Credentials and select OAuth 2.0 Client IDs.
    • Complete the setup by specifying the application type and redirect URI. Redirect URI is given above.
  5. Retrieve Client ID and Secret:
    • Once created, your Client ID will be displayed.
    • Click to download or view your Client Secret and make sure to copy it securely.
  6. Secure Your Credentials: Store the Client ID and Secret safely and use them in your application to integrate Google’s APIs.

A demo is provided for reference:

Once the code is set up and spring boot app is launched, accessing a protected API will trigger the display of a default login page provided by Spring OAuth-client. This page presents social login options through GitHub or Google.After logging through any one, access to the protected api is given.

Social Login through GitHub(Demo):

Social Login through Google(Demo):

And that’s it! You now know how to add social login features to your Spring Boot application using OAuth credentials, making it easier and more secure for users to sign in.

Cheers!

Happy Coding.

Gaurav Sharma
May 6, 2024
Use Unlogged to
mock instantly
record and replay methods
mock instantly
Install Plugin