package enseirb.myinpulse.config; import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole; 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.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; @Configuration public class WebSecurityCustomConfiguration { // CORS configuration @Value("${VITE_APP_URL}") private String frontendUrl; /** * Configure the CORS (Cross Origin Ressource Sharing -- a security feature) configuration. The * only allowed website is the frontend, defined in the .env file. * * @return the CORS configuration used by the backend */ @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(List.of(frontendUrl)); configuration.setAllowedMethods(Arrays.asList("GET", "OPTIONS")); configuration.setAllowedHeaders( Arrays.asList("authorization", "content-type", "x-auth-token")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } /** * Configure the authorisation required for each path. * *
admin endpoints are under /admin/* and entrepreneur are under /entrepreneur/* * *
If endpoints dont require authentication, they are under /unauth/ * * @param http automatically filled in by spring. * @return a securityfilterchain, automatically used by spring. * @throws Exception TODO: figure out when the exception are raised */ @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests( authorize -> authorize .requestMatchers("/entrepreneur/**", "/shared/**") .access(hasRole("REALM_MyINPulse-entrepreneur")) .requestMatchers("/admin/**", "/shared/**") .access(hasRole("REALM_MyINPulse-admin")) .requestMatchers("/unauth/**") .permitAll() .anyRequest() .authenticated()) .oauth2ResourceServer( oauth2 -> oauth2.jwt( jwt -> jwt.jwtAuthenticationConverter( new KeycloakJwtRolesConverter()))); return http.build(); } }