Adding Spring Security
In our previous lessons, we implemented category management with error handling.
Now we'll add security to our blog platform, ensuring that certain operations are protected while keeping our content publicly readable.
This will enable us to implement user authentication and protected endpoints in the following lessons.
Understanding Security Requirements
Let's first ensure we have the necessary dependencies in our pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>Configuring Security Settings
By default, Spring Security requires authentication for all endpoints, which we'll need to customize for our public-facing blog content.
Security configuration in Spring Boot 3.x uses a more modern, functional approach compared to earlier versions.
Let's create a new package com.devtiro.blog.config and implement our intitial SecurityConfig class:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/v1/posts/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/categories/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/tags/**").permitAll()
.anyRequest().authenticated()
)
.csrf(csrf -> csrf.disable())
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
return http.build();
}
}Summary
- Added Spring Security and JWT dependencies for authentication support
- Created security configuration enabling public access to GET endpoints
- Configured stateless session management for JWT-based authentication
- Implemented password encoding with the
DelegatingPasswordEncoder - Set up authentication manager for future user authentication implementation