[Spring Boot] Spring Boot @ enable oauth2sso | enable OAuth2 single sign on

This page will introduce an example of the Spring Security OAuth2 @EnableOAuth2Sso annotation.

@The enable oauth2sso annotation enables OAuth2 single sign on (SSO). By default, all paths need to be secure.

We can use the WebSecurityConfigurerAdapter in the Java configuration of Spring Security to customize it. We can configure Spring Security OAuth2 using application.properties or application.yml or from the command line.

Here we will use GitHub to create a Spring Boot OAuth2 application.

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

Find Maven dependency for OAuth2.

<dependency>
	<groupId>org.springframework.security.oauth.boot</groupId>
	<artifactId>spring-security-oauth2-autoconfigure</artifactId>
	<version>2.1.5.RELEASE</version>
</dependency> 

In Spring Boot applications, the availability of the above dependencies on the classpath provides us with the advantage of automatically configuring OAuth2.

Use @ EnableOAuth2Sso

To use @ EnableOAuth2Sso in our application, please annotate it with @ Configuration in the Spring Security Configuration.

@Configuration
@EnableOAuth2Sso
public class SecurityConfiguration {
} 

Now all URLs need security authentication. We can customize this behavior using the WebSecurityConfigurerAdapter. Suppose we want to use some URLs without security verification, such as home page and error page, which are configured as follows.

SecurityConfiguration.java

package com.concretepage;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
	   @Override
	    protected void configure(HttpSecurity http) throws Exception {
	        http
	            .authorizeRequests()
	            .antMatchers("/", "/error**").permitAll()
                    .anyRequest().authenticated()
                    .and().logout().logoutUrl("/logout")
		    .logoutSuccessUrl("/");

	    }
} 

OAuth2 configuration

In Spring Boot applications, we can configure secure OAuth2 clients, resources, and sso properties using application.properties or application.yml or from the command line.

In our example, we use GitHub OAuth.

application.yml

security:
  oauth2:
   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
   sso:
     login-path: /login 

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

clientId: This is the ID of the OAuth client through which the OAuth provider identifies the client.

clientSecret: the client key associated with the resource.

To get GitHub's OAuth2 client ID and client key, go through the link.

Logout

To log off the Spring Security application, configure the logout URL in the Spring Security Java configuration file, which defaults to / logout, and then create a form and submit it to the logout URL in POST mode. Use Thymeleaf to find the sample form.

<form th:action="@{/logout}" method="POST">
      <input type="submit" value="Logout"/>
</form> 

Complete example

Here we will provide the complete code of our demo program. The SecurityConfiguration.java and application.yml files have been given in the article. Find the rest of the code.

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> 

AppController.java

package com.concretepage;
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() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("welcome");
		return mav;
	}

	@GetMapping("error")
	public ModelAndView error() {
		ModelAndView mav = new ModelAndView();
		return mav;
	}
} 

index.html

<!doctype html>
<html>
<head>
  <title>Spring Security</title>
</head>
<body>
   <h3>Login with <a href="/hello">GitHub</a></h3>
</body>
</html> 

welcome.html

<!doctype html>
<html lang="en">
<head>
    <title>Welcome</title>
</head>
<body>
   Welcome <b th:inline="text" > [[${#httpServletRequest.remoteUser}]] </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>
   <h3>Error</h3>
   <p thif="${param.error}">
       An error occurred.
   </p>
</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 and see the welcome page.

reference

[1]OAuth2 Boot
[2]OAuth 2 Developers Guide

Source download

Extraction code: mao4

spring-boot-enableoauth2sso.zip

Tags: Java Spring Spring Boot sso oauth2

Posted on Mon, 18 Oct 2021 19:03:22 -0400 by SwiftlyTilting