본문 바로가기
프로그래밍

[Spring Boot] 스프링 시큐리티 설정 후 크롤링이 안될 때

by 개발자신입 2024. 7. 2.
반응형

문제

로그인 기능을 구현하기 위해 스프링 시큐리티를 사용하기로 했다. 스프링 시큐리티를 적용하고 난 후에 기존에 되던 기능들이 안되더라. 왜지? 개발자도구 콘솔에서 에러 내용을 보니 news가 login으로 리다이렉트 되고 있었다. 

Access to XMLHttpRequest at 'http://localhost:5000/login' 
(redirected from 'http://localhost:3000/api/news') 
from origin 'http://localhost:3000' has been blocked 
by CORS policy: No 'Access-Control-Allow-Origin' 
header is present on the requested resource.

 

 

해결

스프링 시큐리티 문제인 걸 파악했으니 이제 스프링 시큐리티 클래스를 수정해주면 된다. 

/api/news에 대한 요청을 인증 없이 허가하는 코드를 추가해주면 해결된다.

 

.requestMatchers("/api/**").permitAll()

 


@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
            	.requestMatchers("/api/news").permitAll()
                .anyRequest().authenticated() // 모든 요청에 대해 인증 필요
            )
            .formLogin(formLogin -> formLogin // 기본 폼 로그인 설정
                .loginPage("/login") // 커스텀 로그인 페이지 설정 (옵션)
                .permitAll()
            )
            .logout(logout -> logout
                .logoutUrl("/api/auth/logout") // 로그아웃 URL 설정
                .invalidateHttpSession(true) // 세션 무효화
                .deleteCookies("JSESSIONID") // 쿠키 삭제
                .permitAll()
            );

        return http.build();
    }
    
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

 

반응형

댓글