Spring Boot @EnableOAuth2Sso

By Arvind Rai, January 16, 2020
This page will walk through Spring Security OAuth2 @EnableOAuth2Sso annotation example. The @EnableOAuth2Sso annotation enables OAuth2 Single Sign On (SSO). By default all the paths are secured. We can customize it using WebSecurityConfigurerAdapter in our Spring Security Java Configuration. We can configure Spring Security OAuth2 using application.properties or application.yml or as command line.
Here we will create Spring Boot OAuth2 application using GitHub.

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 Dependency

Find the 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 application the availability of above dependency on your classpath, gives us advantage for auto-configuration of OAuth2.

Using @EnableOAuth2Sso

To use @EnableOAuth2Sso in our application, annotate it in Spring Security Configuration with @Configuration.
@Configuration
@EnableOAuth2Sso
public class SecurityConfiguration {
} 
All the URLs will be secured now. We can customize this behavior using WebSecurityConfigurerAdapter. Suppose we want to use some URLs to be unsecured such as home page and error page etc.
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 application, We can configure Security OAuth2 client, resources and sso properties using application.properties or application.yml or as command line. Here in our example we are using 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 your GitHub clientId and clientSecret in above YML file.
clientId: This is the OAuth client id by which OAuth provider identifies the client.
clientSecret: The client secret associated with the resource.

To get GitHub OAuth2 client id and client secret, go through the link.

Logout

To logout Spring Security application, configure logout URL in Spring Security Java Configuration file, the default is /logout, and then create a form and submit to logout URL as POST method. Find the sample form with Thymeleaf.
<form th:action="@{/logout}" method="POST">
      <input type="submit" value="Logout"/>
</form> 

Complete Example

Here we will provide complete code of our demo application. The files SecurityConfiguration.java and application.yml have already been given above 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 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 @EnableOAuth2Sso
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 and see welcome page.
Spring Boot @EnableOAuth2Sso

References

OAuth2 Boot
OAuth 2 Developers Guide

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us