Spring Boot OAuth2 Login with GitHub Example
- Details
- Written by Nam Ha Minh
- Last Updated on 30 November 2022   |   Print Email
In this Spring Security tutorial, you will learn how to implement login function using GitHub account in a Spring Boot web application. Login using GitHub would be useful for applications with users are developers as almost every developer has account on GitHub.
To follow this tutorial, I suppose that you already have a Spring Boot application in which authentication is implemented with traditional username and password. Then we’ll update it by adding an option “Login with GitHub” in the login page like this:
Technologies: Spring Web, Spring Data JPA, Hibernate, Thymeleaf, Spring Security and Spring OAuth2 Client.
1. Create a GitHub OAuth App
You must have an account on GitHub.com (of course). Follow this video to create your first GitHub OAuth App, then obtain the Client ID and Client Secret code which will be used in the project configuration:
Note that under the app’s settings, you must specify the Authorization callback URL exactly matches a URL of your application, for example:
It is the URL to which the end users will be redirect upon successfully authentication with GitHub.
2. Declare Maven Dependency for Spring Boot OAuth2 Client
Open your project’s pom.xml file and put the following XML snippet:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency>
This dependency is required for using Spring OAuth2 Client library that greatly simplifies integration of Single Sign On based on OAuth2 authorization protocol within a Spring application.
3. Configure Spring OAuth2 Properties for GitHub
Next, update your Spring Boot configuration file (application.yml). Specify the following properties for OAuth2 authentication with GitHub:
spring: security: oauth2: client: registration: github: clientId: YOUR_GITHUB_APP_CLIENT_ID clientSecret: YOUR_GITHUB_APP_CLIENT_SECRET scope: - user:email - read:user
Replace the values of clientId and clientSecret by the ones you obtained when creating your GitHub OAuth App.
4. Update Login Page
Then add the following hyperlink into your custom login page:
<a th:href="/@{/oauth2/authorization/github}">Login with GitHub</a>
Then the users will see the Login with GitHub option in the login page like this:
For more details about using custom login page, read this article: Spring Security Custom Login Page with Thymeleaf, HTML 5 and Bootstrap 4.
5. Code Custom OAuth User and OAuth User Service Classes
Next, create a new class that extends OAuthUser interface as defined by Spring OAuth2 API – with the following code:
package net.codejava; import java.util.Collection; import java.util.Map; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.user.OAuth2User; public class CustomOAuth2User implements OAuth2User { private OAuth2User oauth2User; public CustomeOAuth2User(OAuth2User oauth2User) { this.oauth2User = oauth2User; } @Override public Map<String, Object> getAttributes() { return oauth2User.getAttributes(); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return oauth2User.getAuthorities(); } @Override public String getName() { return oauth2User.getAttribute("name"); } }
Note that this class wraps an instance of OAuth2User, which will be passed by Spring OAuth2 upon successful OAuth authentication. And we override the getName() method to return username associated with GitHub account.
And create a subclass of DefaultOAuth2UserService as follows:
package net.codejava.security.oauth; import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.stereotype.Service; @Service public class CustomOAuth2UserService extends DefaultOAuth2UserService { @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { OAuth2User user = super.loadUser(userRequest); return new CustomOAuth2User(user); } }
Here, we override the loadUser() method which will be called by Spring OAuth2 upon successful authentication, and it returns a new CustomOAuth2User object.
6. Configure Spring Security for OAuth2 Authentication
To integrate single sign on with GitHub with traditional username and password login, update configuration for Spring security as follows:
package net.codejava; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/login").permitAll() .anyRequest().authenticated() .and() .formLogin().permitAll() .loginPage("/login") .and() .oauth2Login() .loginPage("/login") .userInfoEndpoint() .userService(userService) .and() .logout().logoutSuccessUrl("/").permitAll(); } @Autowired private CustomOAuth2UserService userService; }
Pay attention to code snippet that configures OAuth2 login:
http.oauth2Login() .loginPage("/login") .userInfoEndpoint() .userService(userService)
Done. That’s the configuration and code you need to have. We’re now ready to test login using GitHub.
7. Test Login using GitHub
Download the sample project under the Attachments section below. Run the ProductManagerApplication and access the application at http://localhost:8080 URL. Click View all products and the login page appears.
Click Login with GitHub. If you have not signed in your GitHub, you will see the following GitHub login screen:
Enter your GitHub credentials, then you’ll be redirected to the product listing page, as follows:
Note that if you already signed in your GitHub, you will be authenticated automatically without having to sign in again.
Congratulations! You have successfully implemented single sign on login using GitHub in a Spring Boot application with Spring OAuth2 client API. You can download the sample project in the Attachments section below, or clone the sample project from GitHub.
To see the coding steps in action, I strongly recommend you watch the following video:
Related Spring OAuth2 Tutorials:
Related Spring Security Tutorials:
- Spring Security Forgot Password Tutorial
- Spring Security Limit Login Attempts Example
- Spring Security OTP Email Tutorial
- Spring Security Authentication with JPA, Hibernate and MySQL
- Spring Security Role-based Authorization Tutorial
- Spring Security Customize Login and Logout
- How to Get Logged-in User's Details with Spring Security
- Spring Security: Prevent User from Going Back to Login Page if Already logged in
- Spring Security Authentication Success Handler Examples
- Spring Security Authentication Failure Handler Examples
- Spring Security Logout Success Handler Example
- Spring Security Before Authentication Filter Examples
Other Spring Boot Tutorials:
- How to create a Spring Boot Web Application (Spring MVC with JSP/ThymeLeaf)
- Spring Boot CRUD Example with Spring MVC – Spring Data JPA – ThymeLeaf - Hibernate - MySQL
- Spring Boot Hello World RESTful Web Services Tutorial
- Spring Boot Thymeleaf Form Handling Tutorial
- Spring Data JPA Paging and Sorting Examples
- Spring Boot Error Handling Guide
- Spring Boot Logging Basics
Comments