Back End/Spring Boot

[Spring] React 로 헤더 내려주기 (브라우저가 접근할 수 있는 헤더 제어하기)

DevPing9_ 2021. 12. 3. 20:39

 

React 에서 서버에서 내려주는 헤더에 접근하여 무언가 해보고싶었던 분들이 있을 것이다. (나만그런가?)

무튼 React 에서 헤더에 접근하고 싶지만, 헤더의 종류가 몇개 없어 시무룩했던 시간들을 해결한 경험을 공유하고자 한다.

 

 

# 문제 현상

React 에서 Response 를 콘솔에 찍으면 보이는게 몇개 없다.

 

# 개발자도구 -> NetWork 에서 뽑아온 Response Header

 

# React 에서 console.log 를 통해 찍은 Response 객체

 

 

# 해결 방법

서버에서 헤더를 내려줄 때 Access-Control-Expose-Headers 에 브라우저가 접근해도 되는 헤더를 추가해주면 된다.

 

 

# 예시 코드

package com.bookmarkmanager.bookmarkmanager.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import ch.qos.logback.classic.joran.action.ConfigurationAction;


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .cors().configurationSource(corsConfigurationSource())
                    .and()
            .headers().cacheControl().disable().and()
            .csrf().disable()
            ;
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource(){
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("http://localhost:3000");
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        configuration.addExposedHeader("*"); // 모든걸 허용함 

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

 

 

# 풍족한 헤더에 기쁨을 감추지 못함

Set-Cookie 는 빠져있는데, 이건 어떻게 해결해야 할까 ... 😢

 

 

 

 

# Reference

 

교차 출처 리소스 공유 (CORS) - HTTP | MDN

교차 출처 리소스 공유(Cross-Origin Resource Sharing, CORS)는 추가 HTTP 헤더를 사용하여, 한 출처에서 실행 중인 웹 애플리케이션이 다른 출처의 선택한 자원에 접근할 수 있는 권한을 부여하도록 브라

developer.mozilla.org

 

728x90