
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
package com.example.educatback.config;
import com.example.educatback.Auth.CustomAuthenticationFilter;
import com.example.educatback.Auth.CustomLoginAuthenticationEntryPoint;
import com.example.educatback.Auth.ResultHandler.CustomAccessDeniedHandler;
import com.example.educatback.Auth.ResultHandler.CustomAuthenticationFailureHandler;
import com.example.educatback.Auth.ResultHandler.CustomAuthenticationSuccessHandler;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.DelegatingSecurityContextRepository;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.List;
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
private final CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
private final CustomLoginAuthenticationEntryPoint authenticationEntryPoint;
private final AuthenticationConfiguration authenticationConfiguration;
private final CustomAccessDeniedHandler accessDeniedHandler;
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("http://localhost:3000")); // 클라이언트 애플리케이션의 도메인
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(List.of("authorization", "content-type", "x-auth-token"));
configuration.setAllowCredentials(true); // 쿠키를 포함한 요청 허용
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration); // 모든 경로에 대해 이 CORS 정책 적용
return source;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer->AbstractHttpConfigurer.disable());
http
.authorizeHttpRequests(authorize ->
authorize
.requestMatchers("/register", "/login", "/logout", "/").permitAll()// '/register', '/login' 경로는 모두에게 허용
.requestMatchers("/**").authenticated() // '/**' 경로는 인증된 사용자에게만 허용
.anyRequest().permitAll()).cors(cors->cors.configurationSource(corsConfigurationSource()))
// 그 외의 모든 요청은 모두에게 허용
.addFilterBefore(ajaxAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.exceptionHandling(config -> config
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler))
.logout(logout -> logout
.logoutUrl("/logout")
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies("JSESSIONID")
.logoutSuccessHandler((request, response, authentication) -> {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write("Logout Successful");
}));
return http.build();
}
@Bean
public CustomAuthenticationFilter ajaxAuthenticationFilter() throws Exception {
CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter();
customAuthenticationFilter.setAuthenticationManager(authenticationManager());
customAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
customAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);
// **
customAuthenticationFilter.setSecurityContextRepository(
new DelegatingSecurityContextRepository(
new RequestAttributeSecurityContextRepository(),
new HttpSessionSecurityContextRepository()
));
return customAuthenticationFilter;
}
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}