Security Configuration


package com.example.OepAchievers;

import com.example.OepAchievers.Service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
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;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Autowired
private CustomUserDetailsService userDetailsService;

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, CustomUserDetailsService customUserDetailsService) throws Exception {
    http
            .csrf(csrf -> csrf.disable())
            .cors(cors -> cors.configurationSource(corsFilter()))
            .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/swagger-ui/index.html").permitAll()

                    .requestMatchers("/api/users/**").permitAll()
                    //  .requestMatchers("/api/users/register").permitAll()
                    .anyRequest().authenticated()
            )

// .formLogin(form -> form
// .loginProcessingUrl("/api/auth/login")
// .successHandler((request, response, authentication) -> {
// System.out.println("Login successful for user: " + authentication.getName());
// response.setContentType("application/json");
// response.getWriter().write("{"message":"Login successful", "role":"" +
// authentication.getAuthorities().iterator().next().getAuthority() + ""}");
// })
// .failureHandler((request, response, exception) -> {
// System.out.println("Login failed: " + exception.getMessage());
// response.setContentType("application/json");
// response.setStatus(401);
// response.getWriter().write("{"error":"" + exception.getMessage() + ""}");
// })
//)
.userDetailsService(customUserDetailsService)
.httpBasic(Customizer.withDefaults());

    return http.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)throws Exception{
    return authenticationConfiguration.getAuthenticationManager();
}

// @Bean
// public CorsConfigurationSource corsConfigurationSource() {
// CorsConfiguration configuration = new CorsConfiguration();
// configuration.addAllowedOrigin("http;//localhost:3000");
// configuration.addAllowedMethod("POST");
// configuration.setAllowedHeaders(Arrays.asList(""));
// configuration.setExposedHeaders(Arrays.asList("
"));
//// configuration.setAllowCredentials(true);
//
// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// source.registerCorsConfiguration("/**", configuration);
// return source;
// }

@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService);
    authProvider.setPasswordEncoder(passwordEncoder());
    return authProvider;
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}


@Bean
public UrlBasedCorsConfigurationSource corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true); // Allow cookies or authentication headers
    config.addAllowedOrigin("http://localhost:3000"); // Frontend URL
    config.addAllowedHeader("*"); // Allow all headers
    config.addAllowedMethod("GET");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("PUT");// Allow all HTTP methods (GET, POST, PUT, etc.)
    source.registerCorsConfiguration("/**", config);
    return source;
}

}