Files
sumoc-backend/src/main/java/SuMoC/backend/security/SecurityConfiguration.java
T
2025-12-30 23:17:01 +01:00

150 lines
6.7 KiB
Java

package SuMoC.backend.security;
import SuMoC.backend.security.utils.RSAKeyProperties;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
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.List;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
private static final String[] AUTH_WHITELIST = {
"/api/v1/auth/**",
"/v3/api-docs/**",
"/v3/api-docs.yaml",
"/swagger-ui/**",
"/swagger-ui.html",
};
private final RSAKeyProperties keys;
public SecurityConfiguration(RSAKeyProperties keys) {
this.keys = keys;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(UserDetailsService detailsService) {
DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider();
daoProvider.setUserDetailsService(detailsService);
daoProvider.setPasswordEncoder(passwordEncoder());
return new ProviderManager(daoProvider);
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("http://localhost:4200")); // dein Angular-Origin
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(List.of("*"));
config.setAllowCredentials(true); // wichtig für Authorization-Header
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.cors(withDefaults())
//.authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) //allows Access To ALL APIs, Security is off
.authorizeHttpRequests(auth -> {
auth.requestMatchers(AUTH_WHITELIST).permitAll();
auth.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll();
auth.requestMatchers("/routing/alternative/**").permitAll();
auth.requestMatchers("/auth/user/**").permitAll();
auth.requestMatchers("/admin/**").hasRole("ADMIN"); //looks for "ROLE_ADMIN" //alternative: hasAuthoritiy("ADMIN")
auth.requestMatchers("/user/**").hasAnyRole("ADMIN", "USER");
auth.requestMatchers("/friendship/**").hasAnyRole("ADMIN", "USER");
auth.requestMatchers("/trip/**").hasAnyRole("USER", "ADMIN");
auth.requestMatchers("/geocoding/**").hasAnyRole("USER", "ADMIN");
//auth.requestMatchers("/error").permitAll();
auth.anyRequest().authenticated();
}
) //TODO:might be Wrong Configuration, rn working fine.
.oauth2ResourceServer((OAuth2ServerConfigurer) -> {
OAuth2ServerConfigurer.jwt(jwtConfigurer -> {
jwtConfigurer.decoder(this.jwtDecoder());
jwtConfigurer.jwtAuthenticationConverter(jwtAuthenticationConverter());
});
})
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
/* .headers(headers ->
headers.xssProtection(
xss -> xss.headerValue(XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK)
).contentSecurityPolicy(
cps -> cps.policyDirectives("script-src 'self'")
))*/;
return http.build();
}
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(keys.getPublicKey()).build();
}
@Bean
public JwtEncoder jwtEncoder() {
JWK jwk = new RSAKey.Builder(keys.getPublicKey()).privateKey(keys.getPrivateKey()).build();
JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
return new NimbusJwtEncoder(jwks);
}
@Bean
// for spring security, so it can correctly identifiy Roles (identifies roles via "ROLE_[role]")
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
jwtConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
return jwtConverter;
}
}