Spring Boot @EnableOAuth2Client Example

By Arvind Rai, January 21, 2020
This page will walk through Spring Boot @EnableOAuth2Client annotation example. The @EnableOAuth2Client enables for an OAuth2 client configuration in Spring Security Web application. The @EnableOAuth2Client allows using the Authorization Code Grant from one or more OAuth2 Authorization servers. To use @EnableOAuth2Client we need to register OAuth2ClientContextFilter in our application. The @EnableOAuth2Client enables the autowiring of OAuth2ClientContext that can be used to create OAuth2RestTemplate bean.
On this page we will create Spring Boot OAuth2 client application that will use GitHub to login.

Technologies Used

Find the technologies being used in our example.
1. Java 11
2. Spring 5.1.7.RELEASE
3. Spring Boot 2.1.5.RELEASE
4. Maven 3.5.2

Maven Dependencies

Find the Maven dependencies.
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

The OAuth2ClientContext is the OAuth2 Security context that consists access token. We can create OAuth2RestTemplate bean with this as following.
@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 with @EnableOAuth2Client

Find the OAuth2 client configuration used in our example for @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 resource such as client id, client secret etc.
ResourceServerProperties: This is Spring Boot class. It contains OAuth2 resource details.
FilterRegistrationBean: This is Spring Boot class. It registers filters in Servlet 3.0 container in Spring Boot application.
OAuth2ClientContextFilter: This is the security filter for an OAuth2 client.
OAuth2ClientAuthenticationProcessingFilter: This is the OAuth2 client filter that acquires an OAuth2 access token from an authorization server.
OAuth2RestTemplate: Rest template that makes OAuth2-authenticated REST requests.
UserInfoTokenServices: This is Spring Boot class. It is the implementation of ResourceServerTokenServices that uses a user info REST service.

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 above YML file.
To get GitHub OAuth2 client id and client secret, go through the link.

Create Controller and View

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 application.yml file.
Then run the following command from root folder of the project using command prompt.
mvn spring-boot:run 
Access the URL.
http://localhost:8080/ 
Spring Boot @EnableOAuth2Client Example
Click on GitHub link to login. You will be redirected to GitHub login page. After successful login, you will be redirected back to your application.
Spring Boot @EnableOAuth2Client Example

References

Spring Boot and OAuth2
Spring Doc: EnableOAuth2Client

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us