VOOZH about

URL: https://www.geeksforgeeks.org/git/oauth2-authentication-with-spring-and-github/

⇱ OAuth2 Authentication with Spring and Github - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

OAuth2 Authentication with Spring and Github

Last Updated : 17 Jan, 2026

Spring Security provides seamless integration with OAuth2 providers like GitHub, Google or Facebook. This allows developers to enable Single Sign-On (SSO) and let users log in with their GitHub account instead of managing custom login forms and credentials.

What is OAuth2 Authentication

OAuth2 is an industry-standard protocol for authorization. Instead of creating separate credentials for every app, users can log in with a trusted provider (like GitHub) and allow your application to use certain information.

  • Eliminates password storage in your app.
  • Provides secure authentication.
  • Enhances user experience with Single Sign-On.

Steps to Implement OAuth2 Authentication with GitHub

Step 1: Create a GitHub OAuth App

1. Go to GitHub -> Settings -> Developer settings -> OAuth Apps.
2. Click New OAuth App.
3. Fill in the details:

  • Application Name: SpringSecurityOAuthApp
  • Homepage URL: http://localhost:8080/
  • Authorization Callback URL: http://localhost:8080/login/oauth2/code/github

4. Register the app and copy: Client ID & Client Secret.

Step 2: Create Your Spring Boot Project

Use Spring Initializr and create spring boot project

Select:

  • Spring Boot version: 3.2.x
  • Dependencies: Spring Web, Spring Security, Thymeleaf
  • Add the following dependency in your pom.xml to enable OAuth2 login with GitHub:

Note: This dependency is mandatory for OAuth2 authentication. Without it, GitHub login will not work even if Spring Security is present.

Step 3: Configure Application Properties

Add your credentials in application.yml:

Step 4: Create Controller

Create a controller class for define endpoint

Step 5: Create Thymeleaf Views

index.html:

welcome.html

Step 6: Security Configuration

Spring Boot auto-configures OAuth2 login, so you don’t need a custom SecurityConfig.

Step 7: Run the Application

  • Run your Spring Boot app.
  • Visit: http://localhost:8080/
  • Click Login via GitHub -> you’ll be redirected to GitHub login.
  • After successful login, you’ll be redirected to /welcome and see your GitHub username + avatar.
Comment

Explore