package enseirb.myinpulse.config; import enseirb.myinpulse.security.KeycloakJwtRolesConverter; 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.web.SecurityFilterChain; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import java.util.Arrays; import java.util.List; import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole; @Configuration public class WebSecurityCustomConfiguration { // CORS configuration // TODO: make sure to only accept our own domains @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(List.of("*")); configuration.setAllowedMethods(Arrays.asList("GET", "OPTIONS")); configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token")); // Do not remove, this fixes the CORS errors when unauthenticated UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize .requestMatchers("/random2").access(hasRole("REALM_MyINPulse-entrepreneur")) .requestMatchers("/random").access(hasRole("REALM_MyINPulse-admin")) .requestMatchers("/random3").permitAll() .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt. jwtAuthenticationConverter(new KeycloakJwtRolesConverter()))); return http.build(); } }