package com.cygnus.cloud.security; import static org.springframework.security.config.Customizer.withDefaults; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtValidators; import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder; import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder; import org.springframework.security.web.server.SecurityWebFilterChain; @Configuration public class CloudSecurityConfiguration { @Bean SecurityWebFilterChain cloudSecurityFilterChain( ServerHttpSecurity http, CommunicationSecurityProperties properties) { http.csrf(ServerHttpSecurity.CsrfSpec::disable); if (!properties.enabled()) { return http.authorizeExchange(exchange -> exchange.anyExchange().permitAll()).build(); } return http .authorizeExchange(exchange -> exchange .pathMatchers("/actuator/health", "/actuator/info").permitAll() .pathMatchers("/oauth2/token").permitAll() .pathMatchers( "/api/v1/installations/activation/validate", "/api/v1/installations/register") .permitAll() .pathMatchers("/api/v1/identity/login") .hasAuthority("SCOPE_identity.login") .pathMatchers("/api/v1/queries/**") .hasAuthority("SCOPE_identity.login") .pathMatchers("/api/v1/admin/**") .hasAuthority("SCOPE_cygnus.admin") .anyExchange().authenticated()) .oauth2ResourceServer(resourceServer -> resourceServer.jwt(withDefaults())) .build(); } @Bean @ConditionalOnProperty(name = "cygnus.security.enabled", havingValue = "true") ReactiveJwtDecoder reactiveJwtDecoder(CommunicationSecurityProperties properties) { NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder .withPublicKey(PemKeyLoader.publicKey(properties.accessTokenPublicKey())) .build(); decoder.setJwtValidator(new DelegatingOAuth2TokenValidator( JwtValidators.createDefaultWithIssuer(properties.issuerUri()), new AudienceValidator(properties.audience()))); return decoder; } }