HttpSecurity Configuration Deep Dive
Master the `HttpSecurity` configuration to define security rules for various HTTP requests and endpoints.
What is HttpSecurity?
HttpSecurity is a core component in Spring Security. It's like the security guard for your web application's doors.
It lets you define rules for different HTTP requests, controlling who can access which parts of your application and under what conditions.
- Authentication: Who are you? (Are you logged in?)
- Authorization: What are you allowed to do? (Do you have permission?)
Your First Security Chain
You configure HttpSecurity within a SecurityFilterChain bean. This bean defines a chain of filters that Spring Security uses to secure your app.
Here's a minimal setup. Run it and try to access /hello. You'll be redirected to a login page!
Use username: user, password: password.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SecurityApp {
public static void main(String[] args) {
SpringApplication.run(SecurityApp.class, args);
}
@GetMapping("/hello")
public String sayHello() {
return "Hello, secured world!";
}
}
@Configuration
@EnableWebSecurity
class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated() // All requests need authentication
)
.formLogin(form -> form
.permitAll() // Allow everyone to see the login page
)
.logout(logout -> logout
.permitAll()); // Allow everyone to logout
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}All lessons in this course
- Role-Based Access Control (RBAC)
- Method-Level Security with Annotations
- HttpSecurity Configuration Deep Dive
- Securing Endpoints with Custom Access Rules