Spring Boot App Login With GitHub OAuth2
GitHub OAuth2 Configuration
Create a GitHub application to obtain the client ID and client secret.
Configure your Spring Boot application with these credentials in the
application.properties
orapplication.yml
file.
server.port = 8080
spring.security.oauth2.client.registration.github.client-id=
spring.security.oauth2.client.registration.github.client-secret=
Required Dependency
<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>
Security Configuration
package com.hystrix.demo.security;
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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth-> {
auth.requestMatchers("/send").permitAll();
auth.anyRequest().authenticated();
})
.oauth2Login(withDefaults())
.formLogin(withDefaults())
.build();
}
}
Controller
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class homeController {
@GetMapping("/send")
public String emailService() {
return "this is email services ";
}
@GetMapping("/secured")
public String secured() {
return "this is secured services ";
}
}
Test the Application
Run your Spring Boot application and test the GitHub OAuth2 login. Ensure that users can log in using their GitHub credentials.