Create Security Config
Now that we have set up our users in Keycloak, we need to configure Spring Security in our application to protect our endpoints and validate access tokens.
Setting Up the Configuration Class
First, let's create a dedicated package for our configuration classes to keep our code organized.
Create a new package called com.devtiro.restaurant.config.
In this package, we'll create our SecurityConfig class which will manage our application's security settings.
package com.devtiro.restaurant.config;
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.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.web.SecurityFilterChain;
@EnableWebSecurity
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 ->
oauth2.jwt(jwt ->
jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())))
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.csrf(csrf -> csrf.disable())
;
return http.build();
}
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
return new JwtAuthenticationConverter();
}
}Understanding the Configuration
This configuration sets up several key security features for our application.
The @EnableWebSecurity annotation enables Spring Security's web security support.
We configure all endpoints to require authentication with .anyRequest().authenticated().
Since we're building a REST API, we set the session creation policy to STATELESS, meaning no sessions will be created or used.
We've disabled CSRF protection as we're building a stateless REST API, though in production applications you might want to enable it for additional security.
The configuration works with the spring.security.oauth2.resourceserver.jwt.issuer-uri property we set earlier, which tells Spring Security where to validate JWT tokens.
Summary
- Created
SecurityConfigclass to manage application security settings - Configured application to require authentication for all endpoints
- Set up stateless session management for our REST API
- Enabled JWT token validation with Keycloak