Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

OAuth2 Authentication with Spring and Github

OAuth2 is a popular authentication and authorization framework. Many developers use it to provide third-party (e.g., GitHub, Facebook, Google) authentication for their applications. Spring Security provides comprehensive support for integrating OAuth2. In this guide, we'll look at how to set up OAuth2 authentication with Spring and GitHub.

Prerequisites:

  1. Java Development Kit (JDK)
  2. A build tool like Maven or Gradle
  3. An Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse
  4. A GitHub account

Steps:

1. Set up a New Application on GitHub:

  • Go to GitHub Developer Settings and click on New OAuth App.
  • Fill out the form:
    • Application Name: Your App's name.
    • Homepage URL: Your App's homepage (can be a placeholder for now).
    • Authorization callback URL: http://localhost:8080/login/oauth2/code/github (or replace localhost:8080 with your server's address and port).
  • After registering, note down the Client ID and Client Secret for later use.

2. Setting Up a Spring Boot Project:

Start a new Spring Boot project using Spring Initializr. Add the following dependencies:

  • Spring Web
  • Spring Security
  • OAuth2 Client

Or, if you are using Maven, add to your pom.xml:

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

3. Application Configuration:

In src/main/resources/application.yml (or application.properties), add:

spring:
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: YOUR_GITHUB_CLIENT_ID
            client-secret: YOUR_GITHUB_CLIENT_SECRET

Replace YOUR_GITHUB_CLIENT_ID and YOUR_GITHUB_CLIENT_SECRET with the values from the GitHub OAuth App you created.

4. Spring Security Configuration:

Create a configuration class:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/", "/home", "/login**", "/error**").permitAll()
            .anyRequest().authenticated()
            .and()
            .oauth2Login();
    }
}

This configuration sets up basic Spring Security authentication using OAuth2. It also permits some URLs while requiring authentication for others.

5. Run Your Application:

Run your Spring Boot application. Navigate to http://localhost:8080. If everything is set up correctly, you'll be redirected to the GitHub login page when trying to access an authenticated endpoint.

6. Accessing User Information:

After successful authentication, you can access user information using the @AuthenticationPrincipal annotation in your controller methods:

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

Here, OAuth2User gives you access to user attributes returned by GitHub upon successful authentication.

Conclusion:

OAuth2 integration with Spring Boot and GitHub is quite straightforward thanks to Spring Security's OAuth2 support. This setup allows users to authenticate with their GitHub credentials, granting applications access to their GitHub data (as per permissions) and providing a seamless login experience.