In this post, we'll learn how to integrate Spring Boot with Spring Security for authorization and authentication.
Spring Security is a powerful and highly customizable authentication and authorization framework. It's the de-facto standard for securing Spring-based applications.
pom.xml
file:<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
SecurityConfig.java
file and annotate it with @EnableWebSecurity
:@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
SecurityConfig
class to suit your needs. For example, you might want to add a @Configuration
annotation:@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
@EnableGlobalMethodSecurity
to enable method-level security:@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
SecurityConfig
class, override the configure(HttpSecurity)
method to configure security settings:@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
http://localhost:8080/login
. You should see the login page:configure(AuthenticationManagerBuilder)
method and click "Login". You should see the "Welcome" page:You've successfully integrated Spring Boot with Spring Security.