Securing a Spring Boot App with Authorization
First, you’ll need to add the Spring Security dependency to your project. You can do this by adding the following to your “pom.xml” file:
First, you’ll need to add the Spring Security dependency to your project. You can do this by adding the following to your “pom.xml” file:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.4.4</version>
</dependency>
Next, you’ll need to add a “WebSecurityConfigurerAdapter” to your project and override the “configure” method. This is where you’ll configure the rules for securing your app:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}
This configuration will require that all requests to your app are authenticated using either a form login or HTTP basic authentication.
You can also specify more granular rules for which paths are secured and which are not by using the “antMatchers” method. For example:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/\*\*").hasRole("ADMIN")
.antMatchers("/user/\*\*").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
This configuration will require that all requests to paths starting with /admin/ have the role ADMIN, all requests to paths starting with /user/ have either the USER or ADMIN role, and all other requests are authenticated.
I hope this helps! Let me know if you have any other questions.