[SpringBoot] Error - 스프링 시큐리티 적용 시 css 등 static 요소 미반영 에러 (SpringSecurity)

 

원인

  • 파일 : SecurityFilterChain webSecurityFilterChain(HttpSecurity http) throws Exception 메소드 적용하는 java 파일
  • 메시지 : 메시지 없음
  • 코드
@Configuration
@EnableWebSecurity
public class SecurityConfig {

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

	    
	    @Bean
	    protected SecurityFilterChain webSecurityFilterChain(HttpSecurity http) throws Exception {
	        http
	                .authorizeHttpRequests()
	                .requestMatchers(
	                		"/main", 
	                		"/account", 
	                		"/join", 
	                		"/find", 
	                		"/member_static/**"
	                		).permitAll()
	                .anyRequest().authenticated();




	        //CSRF 토큰
	        http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

	        return http.build();
	    }
}

해결방법

.requestMathers("/member_static/**").permitAll() 추가

주석

spring security를 적용하고 나니 css가 적용이 안되서 애를 먹었다.
아무리 구글링을 해봐도, css 등은 .requestMatchers("/css/**").permitAll() 해주세요. 라는 말뿐이었다.
스프링부트 공식 문서를 읽어봐도 도저히 해결책이 안나왔었는데,
생각해보니 타임리프에 css를 th:href를 할 때도 세부 경로를 지정해줘야하는데, 시큐리티 적용할 때도 그래야하지 않을까 생각이 들었다.
그냥 static 하위에 css, js 등 폴더가 있다면 스프링부트가 자동으로 잡겠지만 나는 member 페이지와 admin 페이지 구분을 위해서 static 및에 member_static 를 두고 적용시켰기 때문에 자동 예외처리가 되지 않았던 거였다.

그래서 예외 처리를 위해서 "/member_static/**"를 추가하니 몇 시간 서치했던 게 무색할 정도로 잘 되었다.