[Spring Boot] Spring Boot @EnableOAuth2Client example | log in to your project through Github

This page will introduce an example of Spring Boot @EnableOAuth2Client annotation.

@EnableOAuth2Client allows you to configure the OAuth2 client in the Spring Security Web application.

@EnableOAuth2Client allows authorization using authorization codes from one or more OAuth2 authorization servers.

To use @ EnableOAuth2Client, we need to register the OAuth2ClientContextFilter in our application.

@EnableOAuth2Client allows automatic connection to the OAuth2ClientContext, which can be used to create the OAuth2RestTemplate Bean.

On this page, we will create a Spring Boot OAuth2 client application and log in using GitHub.

Demo tool version

  1. Java 11
  2. Spring 5.1.7.RELEASE
  3. Spring Boot 2.1.5.RELEASE
  4. Maven 3.5.2

Maven dependency

pom.xml

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.1.5.RELEASE</version>
	<relativePath />
</parent>
<properties>
	<context.path>spring-app</context.path>
	<java.version>11</java.version>
</properties>
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-security</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-thymeleaf</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.security.oauth.boot</groupId>
		<artifactId>spring-security-oauth2-autoconfigure</artifactId>
		<version>2.1.5.RELEASE</version>
	</dependency>
</dependencies> 

OAuth2ClientContext

OAuth2ClientContext is an OAuth2 security context composed of access tokens. We can use it to create OAuth2RestTemplate Bean, as shown below.

@Configuration
@EnableOAuth2Client
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	OAuth2ClientContext oauth2ClientContext;

	@Bean
	public OAuth2RestOperations restTemplate(OAuth2ClientContext oauth2ClientContext) {
	        return new OAuth2RestTemplate(githubClient(), oauth2ClientContext);
	}
	  
	@Bean
	@ConfigurationProperties("github.client")
	public AuthorizationCodeResourceDetails githubClient() {
		return new AuthorizationCodeResourceDetails();
	}
        ------
} 

OAuth2 client Security configuration using @ enableouth2client

Find the OAuth2 client configuration used in our example for the @ EnableOAuth2Client demo.

SecurityConfig.java

package com.concretepage;
import javax.servlet.Filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

@Configuration
@EnableOAuth2Client
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	OAuth2ClientContext oauth2ClientContext;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/", "/login**", "/error**").permitAll().anyRequest().authenticated()
		        .and().logout().logoutUrl("/logout").logoutSuccessUrl("/")
		        .and().addFilterBefore(oauth2ClientFilter(), BasicAuthenticationFilter.class);

	}

	@Bean
	@ConfigurationProperties("github.client")
	public AuthorizationCodeResourceDetails githubClient() {
		return new AuthorizationCodeResourceDetails();
	}

	@Bean
	@ConfigurationProperties("github.resource")
	public ResourceServerProperties githubResource() {
		return new ResourceServerProperties();
	}
	
	@Bean
	public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(
			OAuth2ClientContextFilter filter) {
		FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
		registration.setFilter(filter);
		registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
		return registration;
	}	
	
	private Filter oauth2ClientFilter() {
		OAuth2ClientAuthenticationProcessingFilter oauth2ClientFilter = new OAuth2ClientAuthenticationProcessingFilter(
				"/login/github");
		OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(githubClient(), oauth2ClientContext);
		oauth2ClientFilter.setRestTemplate(restTemplate);
		UserInfoTokenServices tokenServices = new UserInfoTokenServices(githubResource().getUserInfoUri(),
				githubClient().getClientId());
		tokenServices.setRestTemplate(restTemplate);
		oauth2ClientFilter.setTokenServices(tokenServices);
		return oauth2ClientFilter;
	}	
} 

AuthorizationCodeResourceDetails: details of OAuth2 protected resources, such as customer ID, customer key, etc.

ResourceServerProperties: This is the Spring Boot class. It contains the details of the OAuth2 resource.

FilterRegistrationBean: This is a Spring Boot class. It registers filters in the Servlet 3.0 container of the Spring Boot application.

OAuth2ClientContextFilter: This is a security filter for OAuth2 clients.

OAuth2ClientAuthenticationProcessingFilter: This is an OAuth2 client filter that obtains the OAuth2 access token from the authorization server.

OAuth2RestTemplate: Refactoring template for REST requests for OAuth2 authentication.

UserInfoTokenServices: This is a Spring Boot class. It is the implementation of ResourceServerTokenServices and uses user information REST services.

Find the YML file used in our example.

application.yml

github:
  client:
    clientId: <your_github_clientId>
    clientSecret: <your_github_clientSecret>
    accessTokenUri: https://github.com/login/oauth/access_token
    userAuthorizationUri: https://github.com/login/oauth/authorize
    clientAuthenticationScheme: form
  resource:
    userInfoUri: https://api.github.com/user 

You need to enter your GitHub clientId and clientSecret in the above YML file.

To obtain the OAuth2 client ID and client Secret of GitHub, please use the link.

Create controllers and views

AppController.java

package com.concretepage;
import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class AppController {
	@GetMapping("hello")
	public ModelAndView welcome(Principal principal) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("welcome");
		mav.addObject("name", principal.getName());
		return mav;
	}
} 

index.html

<!doctype html>
<html>
<head>
  <title>Spring Security</title>
</head>
<body>
<h3>
<a href="/login/github" th:href="@{/hello}" th:if="${#httpServletRequest?.remoteUser != undefined }">
      Go to Dashboard
</a>
<a href="/hello" th:href="@{/login/github}" th:if="${#httpServletRequest?.remoteUser == undefined }">
      Login with GitHub
</a>
</h3>                
</body>
</html> 

welcome.html

<!doctype html>
<html lang="en">
<head>
    <title>Welcome</title>
</head>
<body>
   Welcome <b th:inline="text"> [[${name}]] </b> <br/><br/>
   <form th:action="@{/logout}" method="POST">
        <input type="submit" value="Logout"/>
   </form>	
</body>
</html> 

error.html

<!doctype html>
<html>
<head>
  <title>Spring Security</title>
</head>
<body>
  An error occurred.
</body>
</html> 

Main.java

package com.concretepage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main {
	public static void main(String[] args) {
		SpringApplication.run(Main.class, args);
	}
} 

output

Download the project and enter your GitHub clientId and clientSecret in the application.yml file.

Then use the command prompt to run the following command from the root folder of the project.

mvn spring-boot:run 

Visit website

http://localhost:8080/ 


Click the GitHub link to log in. You will be redirected to the GitHub login page. After successful login, you will be redirected to your application.

reference

[1]Spring Boot and OAuth2
[2]Spring Doc: EnableOAuth2Client

Source download

Extraction code: mao4
spring-boot-enableoauth2client.zip

Tags: Java Spring Spring Boot

Posted on Tue, 19 Oct 2021 00:21:41 -0400 by philhale