- JwtAuthenticationFilter now extracts the "role" claim from the JWT
token and creates a SimpleGrantedAuthority("ROLE_" + role.toUpperCase())
on the authentication token. Previously the authorities list was
always empty (only userDetails.getAuthorities() which returned List.of())
- SecurityConfig adds .requestMatchers("/api/admin/**").hasRole("ADMIN")
so admin endpoints require the ROLE_ADMIN authority
- All existing endpoints remain authenticated() only — no existing user
flow is affected
- Public endpoints (auth, webhooks, vehicles) still permitAll()
46 lines
2 KiB
Java
46 lines
2 KiB
Java
package se.bilhalsning.config;
|
|
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
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.crypto.bcrypt.BCryptPasswordEncoder;
|
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
|
import org.springframework.security.web.SecurityFilterChain;
|
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
|
import se.bilhalsning.security.JwtAuthenticationFilter;
|
|
import se.bilhalsning.security.JwtService;
|
|
|
|
@Configuration
|
|
@EnableWebSecurity
|
|
public class SecurityConfig {
|
|
|
|
@Bean
|
|
public PasswordEncoder passwordEncoder() {
|
|
return new BCryptPasswordEncoder();
|
|
}
|
|
|
|
@Bean
|
|
public JwtService jwtService(@Value("${app.jwt.secret}") String secret) {
|
|
return new JwtService(secret);
|
|
}
|
|
|
|
@Bean
|
|
public SecurityFilterChain securityFilterChain(HttpSecurity http,
|
|
JwtAuthenticationFilter jwtAuthenticationFilter) throws Exception {
|
|
http
|
|
.csrf(csrf -> csrf.disable())
|
|
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
|
.authorizeHttpRequests(auth -> auth
|
|
.requestMatchers("/api/auth/register", "/api/auth/login").permitAll()
|
|
.requestMatchers("/api/webhooks/**").permitAll()
|
|
.requestMatchers("/api/vehicles/**").permitAll()
|
|
.requestMatchers("/api/admin/**").hasRole("ADMIN")
|
|
.anyRequest().authenticated())
|
|
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
|
|
|
return http.build();
|
|
}
|
|
}
|