Spring Framework Tutorial
Software Setup and Configuration (STS/Eclipse/IntelliJ)
Core Spring
Spring Annotations
Spring Data
Spring JDBC
Spring Security
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.
New OAuth App
.localhost:8080
with your server's address and port).Client ID
and Client Secret
for later use.Start a new Spring Boot project using Spring Initializr. Add the following dependencies:
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>
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.
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.
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.
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.
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.