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:

Login Page with GitHub

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:

GitHub App

Note that under the app’s settings, you must specify the Authorization callback URL exactly matches a URL of your application, for example:

callback URL



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:

Login Page with GitHub

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:

GitHub App Login

Enter your GitHub credentials, then you’ll be redirected to the product listing page, as follows:

Product Listing After Login

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:

 

Other Spring Boot Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (ProductManagerGitHubLogin.zip)ProductManagerGitHubLogin.zip[Sample Spring Boot project]91 kB

Add comment

   


Comments 

#5Nikhil2023-09-23 01:10
Very nice information shared. Thank you.
Quote
#4Joseph Crypto2021-10-12 05:10
thank for this project nam! I learn from you a lot bro! Thank you.
Quote
#3Aziz2021-04-20 01:28
can you help me for this question? stackoverflow.com/.../...
Quote
#2Nam2021-04-19 22:02
I'm very fine, Aziz. Thanks.
Quote
#1Aziz2021-04-19 03:24
Hi. How are you? i hope you r good.
Quote