[Start Spring Boot] Spring Security CORS

·2024년 4월 15일
0

Start Spring Boot!

목록 보기
41/53
post-thumbnail

CORS

What is?

  • Cross-Origin Resource Sharing
  • 교차 출처 리소스 공유
  • 웹 페이지 상의 제한된 리소스를 최초 자원이 서비스된 도메인 밖의 다른 도메인으로부터 요청할 수 있게 허용하는 구조
  • 도메인이 다르면 요청을 허용받아야함

CORS 맛보기

간단하게 team을 불러오는 리액트 페이지를 구성하였다.

다음과 같이 CORS 오류가 발생한다.

CORS 해결하기1

@CrossOrigin(origins="*") //Will allow any domain
@CrossOrigin(origins="http://localhost:3000") //Will allow any domain
  • 다음과 같은 코드를 Controller에 붙여서 해결할 수 있다.

CORS 해결하기2

  • SpringSecurityConfiguration.java
    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http.cors().configurationSource(new CorsConfigurationSource() {
            @Override
            public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
                CorsConfiguration config = new CorsConfiguration();
                config.setAllowedOrigins(List.of("http://localhost:3000"));
                config.setAllowedMethods(List.of("GET", "POST"));
                config.setAllowCredentials(true);
                config.setAllowedHeaders(List.of("*"));
                config.setExposedHeaders(List.of("Authorization"));
                config.setMaxAge(1800L);
                return config;
            }
        }).and().csrf().disable();

        return http.build();
    }
    
  • 다음과 같이 CorsConfiguration을 구현해서 설정할 수 있다.
  • setAllowedOrigins: 접속을 허용할 주소를 설정
  • setAllowedMethods: 허용 할 메서드를 설정
  • setAllowCredentials: 인증 정보를 포함한 요청을 허용
  • setExposedHeaders: "Authorization" 헤더를 응답에서 클라이언트가 접근할 수 있도록 함
  • setMaxAge: 브라우저가 CORS 응답을 캐시할 시간을 설정
profile
백엔드 개발자가 꿈인 컴공과

0개의 댓글

관련 채용 정보