This tutorial aims to guide you through the process of implementing security in your Spring applications using Spring Security, a powerful and highly customizable authentication and access-control framework for Java applications.
By the end of this tutorial, you will be able to:
Prerequisites:
Spring Security provides two main areas of security: Authentication (who are you?) and Authorization (what are you allowed to do?). Let's explore how to implement these in a Spring application.
Spring Security supports a wide variety of authentication models, but the most common one is form-based authentication. Here's how to set it up:
pom.xml
file:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
WebSecurityConfigurerAdapter
:@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
In the above code, anyRequest().authenticated()
means that any incoming request must be authenticated, and formLogin()
enables form-based authentication.
Authorization refers to the process of deciding whether a user is allowed to perform an action. You can specify access-control rules in the configure(HttpSecurity http)
method:
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated();
In the above code, only users with the role "ADMIN" can access URLs starting with "/admin", and users with role "USER" or "ADMIN" can access URLs starting with "/user".
Now let's see a full example of a Spring Security configuration:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("password")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
In the configureGlobal(AuthenticationManagerBuilder auth)
method, we're setting up an in-memory user store with a single user. That user is given a username "user", password "password", and a role of "USER".
In this tutorial, we've learned how to implement authentication and authorization in a Spring application using Spring Security. You've seen how to setup form-based authentication, specify access-control rules, and define an in-memory user store.
For further learning, you can explore how to use Spring Security with a real database, and how to customize the login form.
Tips for further practice: Try to implement Spring Security with a real database, and explore other features of Spring Security like OAuth2, JWT, etc.