If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:
>> LEARN SPRING SECURITYMocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
In this tutorial, weβll discuss how to implement SSO β Single Sign On β using Spring Security OAuth and Spring Boot.
Weβll use three separate applications:
- An Authorization Server β which is the central authentication mechanism
- Two Client Applications: the applications using SSO
Very simply put, when a user tries to access a secured page in the client app, theyβll be redirected to authenticate first, via the Authentication Server.
And weβre going to use the Authorization Code grant type out of OAuth2 to drive the delegation of authentication.
Note: this article is using the Spring OAuth legacy project. For the version of this article using the new Spring Security 5 stack, have a look at our article Simple Single Sign-On with Spring Security OAuth2.
2. The Client App
Letβs start with our Client Application; weβll, of course, use Spring Boot to minimize the configuration:
2.1. Maven Dependencies
First, we will need the following dependencies in our pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
2.2. Security Configuration
Next, the most important part, the security configuration of our client application:
@Configuration
@EnableOAuth2Sso
public class UiSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**")
.permitAll()
.anyRequest()
.authenticated();
}
}
The core part of this configuration is, of course, the @EnableOAuth2Sso annotation weβre using to enable Single Sign On.
Note that we need to extend the WebSecurityConfigurerAdapter β without it, all the paths will be secured β so the users will be redirected to log in when they try to access any page. In our case here, the index and login pages are the only pages that can be accessed without authentication.
Finally, we also defined a RequestContextListener bean to handle requests scopes.
And the application.yml:
server:
port: 8082
servlet:
context-path: /ui
session:
cookie:
name: UISESSION
security:
basic:
enabled: false
oauth2:
client:
clientId: SampleClientId
clientSecret: secret
accessTokenUri: http://localhost:8081/auth/oauth/token
userAuthorizationUri: http://localhost:8081/auth/oauth/authorize
resource:
userInfoUri: http://localhost:8081/auth/user/me
spring:
thymeleaf:
cache: false
A few quick notes:
- we disabled the default Basic Authentication
- accessTokenUri is the URI to obtain the Access Tokens
- userAuthorizationUri is the authorization URI that users will be redirected to
- userInfoUri the URI of user endpoint to obtain current user details
Also note that, in our example here, we rolled out our Authorization Server, but of course we can also use other, third-party providers such as Facebook or GitHub.
2.3. Front End
Now, letβs take a look at the front-end configuration of our client application. Weβre not going to focus on that here, mainly because we already covered in on the site.
Our client application here has a very simple front-end; hereβs the index.html:
<h1>Spring Security SSO</h1>
<a href="securedPage">Login</a>
And the securedPage.html:
<h1>Secured Page</h1>
Welcome, <span th:text="${#authentication.name}">Name</span>
The securedPage.html page needed the users to be authenticated. If a non-authenticated user tries to access securedPage.html, theyβll be redirected to the login page first.
3. The Auth Server
Now letβs discuss our Authorization Server here.
3.1. Maven Dependencies
First, we need to define the dependencies in our pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
3.2. OAuth Configuration
Itβs important to understand that weβre going to run the Authorization Server and the Resource Server together here, as a single deployable unit.
Letβs start with the configuration of our Resource Server β which doubles as our primary Boot application:
@SpringBootApplication
@EnableResourceServer
public class AuthorizationServerApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(AuthorizationServerApplication.class, args);
}
}
Then, weβll configure our Authorization server:
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Override
public void configure(
AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("SampleClientId")
.secret(passwordEncoder.encode("secret"))
.authorizedGrantTypes("authorization_code")
.scopes("user_info")
.autoApprove(true)
.redirectUris(
"http://localhost:8082/ui/login","http://localhost:8083/ui2/login");
}
}
Note how weβre only enabling a simple client using the authorization_code grant type.
Also, note how autoApprove is set to true so that weβre not redirected and promoted to manually approve any scopes.
3.3. Security Configuration
First, weβll disable the default Basic Authentication, via our application.properties:
server.port=8081
server.servlet.context-path=/auth
Now, letβs move to the configuration and define a simple form login mechanism:
@Configuration
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login", "/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("john")
.password(passwordEncoder().encode("123"))
.roles("USER");
}
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
Note that we used simple in-memory authentication, but we can simply replace it with a custom userDetailsService.
3.4. User Endpoint
Finally, we will create our user endpoint we used earlier in our configuration:
@RestController
public class UserController {
@GetMapping("/user/me")
public Principal user(Principal principal) {
return principal;
}
}
Naturally, this will return the user data with a JSON representation.
4. Conclusion
In this quick tutorial, we focused on implementing Single Sign-On using Spring Security Oauth2 and Spring Boot.
