OAuth2 Login in Java: Google and GitHub with Spring Boot

by Didin J. on Jun 21, 2025 OAuth2 Login in Java: Google and GitHub with Spring Boot

Learn how to implement OAuth2 login in Java Spring Boot using Google and GitHub providers with secure authentication and user info display.

OAuth2 is the modern industry standard protocol for authorization, allowing applications to securely access user information without handling passwords. It’s widely used by popular services such as Google, GitHub, Facebook, and many others.

In this tutorial, you’ll learn how to implement OAuth2 login in a Java Spring Boot application using Google and GitHub as the authentication providers.

By the end of this guide, you’ll have a working application where users can:

  • Log in with their Google or GitHub accounts

  • View their authenticated user information

  • Log out securely

Why Use OAuth2 Login?

  • User convenience: No need to register or remember another password

  • Security: Delegates authentication to trusted providers

  • Faster onboarding: Great for both personal projects and production-ready apps

This tutorial utilizes Spring Boot 3.x and Spring Security 6, which provide built-in support for OAuth2 client login, making it easier than ever to integrate third-party identity providers, such as Google and GitHub.


Prerequisites

Before diving into the implementation, make sure you have the following tools and accounts ready:

✅ Tools & Technologies

  • Java 17 or higher – Required for Spring Boot 3.x

  • Maven or Gradle – Build tool (this tutorial will use Maven)

  • Spring Boot 3.x

  • An IDE – IntelliJ IDEA, Eclipse, or VS Code

  • Web browser – For testing the login flows

🌐 Accounts Needed

To configure OAuth2 login, you need:

You’ll be registering OAuth2 applications in both platforms to obtain:

  • Client ID

  • Client Secret

  • Redirect URI: Typically http://localhost:8080/login/oauth2/code/{provider} (e.g., /google, /github)


Create a Spring Boot Project

We'll start by generating a new Spring Boot project with the required dependencies for OAuth2 login.

1️⃣ Generate a Project with Spring Initializr

Go to https://start.spring.io and use the following configuration:

  • Project: Maven

  • Language: Java

  • Spring Boot: 3.5.3 (latest stable)

  • Group: com.djamware

  • Artifact: oauth2login

  • Name: oauth2login

  • Packaging: Jar

  • Java Version: 17 or above

📦 Dependencies to Add:

  • Spring Web

  • Spring Security

  • OAuth2 Client

  • Thymeleaf (optional, for simple UI rendering)

💡 You can also generate with curl or IntelliJ's Spring Initializr integration.

OAuth2 Login in Java: Google and GitHub with Spring Boot - Spring Initalizr

2️⃣ Directory Structure (after extraction)

OAuth2 Login in Java: Google and GitHub with Spring Boot

3️⃣ Main Class

package com.djamware.oauth2login;

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

@SpringBootApplication
public class Oauth2loginApplication {

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

}

In the next section, we’ll configure OAuth2 apps on Google and GitHub, and plug the credentials into application.properties.


Configure Google and GitHub OAuth2 Apps

To enable OAuth2 login, you need to register your Spring Boot app with Google and GitHub to obtain the client ID, client secret, and set up the correct redirect URIs.

🌐 1. Google OAuth2 App Setup

🔹 Step-by-Step

  1. Go to Google Cloud Console.

  2. Create a new project or select an existing one.

  3. In the left menu, go to APIs & Services → Credentials.

  4. Click + Create Credentials → OAuth client ID.

  5. If prompted, configure the OAuth consent screen:

    • Choose External for user type

    • Fill in required fields (App name, support email, etc.)

    • Add scopes if needed (default is usually enough for login)

    • Save and continue

  6. Choose Web application as the application type.

  7. Set Authorized redirect URIs to:

    http://localhost:8080/login/oauth2/code/google
  8. Click "Create," and then copy the Client ID and Client Secret.

🐱 2. GitHub OAuth2 App Setup

🔹 Step-by-Step

  1. Go to GitHub Developer Settings.

  2. Under OAuth Apps, click New OAuth App.

  3. Fill in:

    • Application name: e.g., Spring OAuth2 App

    • Homepage URL: http://localhost:8080

    • Authorization callback URL:

      http://localhost:8080/login/oauth2/code/github
  4. Click Register application.

  5. Copy the Client ID and Client Secret.

Once both are set up, you're ready to plug these values into your Spring Boot app’s application.properties.


Application Properties Configuration

Now that you have the Client IDs and Client Secrets from both Google and GitHub, let’s configure them in the Spring Boot application.

Open src/main/resources/application.properties and add the following:

# Server port (optional)
server.port=8080

# OAuth2 - Google Configuration
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.google.scope=openid, profile, email

# OAuth2 - GitHub Configuration
spring.security.oauth2.client.registration.github.client-id=YOUR_GITHUB_CLIENT_ID
spring.security.oauth2.client.registration.github.client-secret=YOUR_GITHUB_CLIENT_SECRET
spring.security.oauth2.client.registration.github.scope=user:email

# Optional: Set default login page
spring.security.oauth2.client.provider.github.authorization-uri=https://github.com/login/oauth/authorize
spring.security.oauth2.client.provider.github.token-uri=https://github.com/login/oauth/access_token
spring.security.oauth2.client.provider.github.user-info-uri=https://api.github.com/user
spring.security.oauth2.client.provider.github.user-name-attribute=login

🔐 Never commit these credentials to version control. For production, use environment variables or a secrets manager.

✅ What This Does:

  • Tells Spring Security where to send users to authenticate.

  • Configures which scopes to request (e.g., email, profile).

  • Enables Spring Boot’s auto-configured OAuth2 login flow.

In the next section, we’ll optionally customize the Spring Security behavior using a SecurityFilterChain bean (especially if you want to control routes or customize login/logout behavior).


Security Configuration

Spring Boot 3 and Spring Security 6 provide smart auto-configuration for OAuth2 login. However, for more control over the authentication process (e.g., public vs secured endpoints, logout, custom login success handling), we’ll define a custom SecurityFilterChain.

🛠️ 1. Create a Security Configuration Class

Create a new file SecurityConfig.java in the same package as your main application class (com.djamware.oauth2login):

package com.djamware.oauth2login;

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

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/", "/login").permitAll()
                .anyRequest().authenticated()
            )
            .oauth2Login(oauth2 -> oauth2
                .loginPage("/login") // Custom login page (optional)
            )
            .logout(logout -> logout
                .logoutSuccessUrl("/")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
            );
        return http.build();
    }
}

✅ What This Does:

  • Allows public access to / and /login.

  • Protects all other endpoints (e.g., /user).

  • Configures Spring OAuth2 login with a custom login page (optional).

  • Enables logout and redirects to the homepage after logging out.


Create Controller and UI

In this section, we’ll:

  1. Create a controller to handle basic routes.

  2. Add Thymeleaf templates to render login options and user info.

🧑‍💻 1. Create the Main Controller

Create HomeController.java under com.djamware.oauth2login:

package com.djamware.oauth2login;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String index() {
        return "index"; // index.html
    }

    @GetMapping("/user")
    public String user(Model model, @AuthenticationPrincipal OAuth2User principal) {
        model.addAttribute("name", principal.getAttribute("name"));
        model.addAttribute("email", principal.getAttribute("email"));
        model.addAttribute("attributes", principal.getAttributes());
        return "user"; // user.html
    }

    @GetMapping("/login")
    public String login() {
        return "login"; // custom login page
    }
}

🧾 2. Create Thymeleaf Templates

Ensure you have spring-boot-starter-thymeleaf added.

📁 Create src/main/resources/templates/index.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>OAuth2 Login App</title>
</head>
<body>
    <h1>Welcome to Spring Boot OAuth2 Login</h1>
    <a th:href="@{/oauth2/authorization/google}">Login with Google</a><br>
    <a th:href="@{/oauth2/authorization/github}">Login with GitHub</a>
</body>
</html>

📁 Create user.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User Page</title>
</head>
<body>
    <h1>User Info</h1>
    <p>Name: <span th:text="${name}"></span></p>
    <p>Email: <span th:text="${email}"></span></p>
    <h3>All Attributes:</h3>
    <pre th:text="${attributes}"></pre>
    <a th:href="@{/logout}">Logout</a>
</body>
</html>

📁 Optionally, create login.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Custom Login</title>
</head>
<body>
    <h1>Login Options</h1>
    <a th:href="@{/oauth2/authorization/google}">Login with Google</a><br>
    <a th:href="@{/oauth2/authorization/github}">Login with GitHub</a>
</body>
</html>

With this setup, visiting / shows login options, /user displays user info after authentication, and /logout logs the user out.


Run and Test the Application

Let’s verify the OAuth2 login flow with Google and GitHub.

▶️ 1. Run the Application

From the project root, run the Spring Boot app using Maven:

./mvnw spring-boot:run

Or, if you use an IDE like IntelliJ, just click Run on the main class OAuth2LoginApplication.

By default, the app runs at:
📍 http://localhost:8080/

🌐 2. Open the Homepage

Visit:
http://localhost:8080/

You should see a simple page with:

  • Login with Google

  • Login with GitHub

🔑 3. Test Google Login

  1. Click Login with Google

  2. You’ll be redirected to Google’s login screen

  3. After logging in, you’ll be redirected to /user

  4. You should see your Google name, email, and raw user attributes

🐱 4. Test GitHub Login

  1. Go back to / or /login

  2. Click Login with GitHub

  3. Authorize the app

  4. You’ll see your GitHub username, email (if available), and raw user attributes

📝 Note: GitHub users may have a private email. You can add the user:email scope to fetch public or verified email addresses.

🔓 5. Logout

Visit /logout or click the Logout link on the /user page.
You’ll be redirected back to the home page.

✅ Congratulations! You now have a working Spring Boot application that supports OAuth2 login via Google and GitHub.

Next, we’ll cover how to extract and manage authenticated user info, and optionally store it or customize sessions.


Handling User Info

After a user logs in via OAuth2, Spring Security injects an OAuth2User object containing all profile attributes returned by the provider (Google or GitHub). You can use this object to:

  • Display the user's name or email

  • Customize the user experience

  • Save or sync user data to a local database

📦 1. Access User Attributes

You’ve already done this in /user route via:

@AuthenticationPrincipal OAuth2User principal

This principal contains a map of all attributes. For example:

principal.getAttribute("name");     // Display name
principal.getAttribute("email");    // Email address
principal.getAttribute("login");    // GitHub username

Use conditional logic depending on the provider. Here’s a more robust example:

String name = (String) principal.getAttribute("name");
String email = (String) principal.getAttribute("email");
String login = (String) principal.getAttribute("login"); // Only for GitHub

model.addAttribute("name", name != null ? name : login);
model.addAttribute("email", email != null ? email : "Email not provided");

🧠 2. (Optional) Save Users to a Local Database

If you want to persist authenticated users, follow these steps:

  1. Add JPA and H2/PostgreSQL/MySQL dependencies

  2. Create a User entity

  3. On each login, extract and save user info (inside a custom OAuth2UserService)

  4. Track first-time vs returning users

Would you like to include this full local database persistence flow in the tutorial?

📤 3. Customize Login Success Behavior (Optional)

If you want to log or track logins:

@Bean
public OAuth2UserService<OAuth2UserRequest, OAuth2User> customOAuth2UserService() {
    return request -> {
        OAuth2UserService<OAuth2UserRequest, OAuth2User> delegate = new DefaultOAuth2UserService();
        OAuth2User oAuth2User = delegate.loadUser(request);

        // Do something with oAuth2User.getAttributes()
        System.out.println("User Logged In: " + oAuth2User.getAttribute("name"));

        return oAuth2User;
    };
}

You can plug this into your SecurityFilterChain if needed.


Logout and Session Handling

Spring Security handles logout and session invalidation out of the box, but here’s how you can fine-tune it for OAuth2 login.

🚪 1. Enable Logout Behavior (already done)

In SecurityConfig.java, you already included:

.logout(logout -> logout
    .logoutSuccessUrl("/")
    .invalidateHttpSession(true)
    .deleteCookies("JSESSIONID")
)

This does the following:

  • Logs the user out

  • Invalidates the current HTTP session

  • Deletes the JSESSIONID cookie

  • Redirects to / after logout

🔗 2. Add Logout Link in UI

In user.html, we already have:

<a th:href="@{/logout}">Logout</a>

Clicking this will:

  • Log the user out of your app

  • Not log them out of Google or GitHub (they’ll stay signed in on those platforms)

🔐 If you want single logout (SLO) from Google/GitHub too, you’d need to integrate provider-specific logout URLs — most apps don’t do this due to UX concerns.

🧼 3. Session Cleanup

Spring handles session cleanup when invalidateHttpSession(true) is enabled. To verify this:

  1. Login

  2. Visit /user

  3. Logout

  4. Try visiting /user again — it should redirect to the login page

🔒 4. Customize Session Timeout (Optional)

In application.properties, you can control the session timeout:

server.servlet.session.timeout=30m

You can also track sessions with a HttpSessionListener if you need logging or monitoring.


Conclusion

In this tutorial, you learned how to build a secure OAuth2 login system in a Java Spring Boot 3.x application using Google and GitHub as authentication providers.

Key Takeaways

  • Set up OAuth2 apps on Google and GitHub

  • Configured Spring Boot with Spring Security and OAuth2 client support

  • Created a custom login flow using Thymeleaf templates

  • Displayed authenticated user info securely

  • Handled session and logout behavior

Spring Security’s built-in OAuth2 support makes it easy to delegate authentication to trusted identity providers, reducing your need to manage passwords and improving your app’s security posture.

You can get the full source code on our GitHub.

That's just the basics. If you need more deep learning about Java and Spring Framework, you can take the following cheap course:

Thanks!