티스토리 뷰
웹 개발을 하다 보면 항상 마주치는 순간이 CORS(Cross-Origin Resource Sharing) 에러이다.
클라이언트 서버와 API 서버의 포트가 다르면 자주 발생하는 에러이다. 그래서 에러가 발생하는 순간 '아! 이건 서버에서 처리를 해주어야겠다' 생각이 들 것이다.
간단한 해결 방법으로, Access-Control-Allow-Origin을 이용해 서버 측에서 클라이언트의 포트를 열어주면 된다.
하지만, 우리가 원하는 것은 로그인 이후의 동작 등과 같이 인증과 관련된 데이터를 담거나 받고 싶을 때이다.
withCredentials Option
기본적으로 브라우저가 제공하는 요청 API 들은 별도의 옵션 없이 인증과 관련된 데이터를 함부로 요청 데이터에 담지 않도록 되어있다. 이는 응답을 받을 때도 마찬가지이다.
이를 해결하기 위한 옵션이 바로withCredentials옵션이다.
withCredentials옵션은 단어 그대로, 다른 도메인(Cross Origin)에 요청을 보낼 때 요청에 인증(credential)정보를 담아서 보낼 지를 결정하는 항목이다.
클라이언트에서의 처리
- axios
axios.post(
'https://example.com/users/login',
{
// SOMETHING BODY DATA
},
{
withCredentials: true,
},
);
- fetch
fetch("https://example.com/users/login", {
method: "POST",
credentials: "include"
})
서버에서의 처리
서버에서는 허용해 주어야 할 옵션들은 와일드카드(*)를 사용 하지 말고 정확히 기재해주어야 한다.
- spring (@CrossOrigin 어노테이션)
@CrossOrigin(origins = "https://example.com, withCredentials = "true" )
@PostMapping("/users")
public void someApi() {}
- spring (서버 전역적으로 CORS 설정) 추천
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080")
.allowedMethods("GET", "POST")
.allowCredentials(true)
}
}
https://velog.io/@ojin0104/spring-boot-cors%EC%97%90%EB%9F%AC-%ED%95%B4%EA%B2%B0Spring-securityreact
- Total
- Today
- Yesterday
- 고정
- React
- zoom
- useReducer
- background-attachment
- this
- window.location
- touchableopacity
- bind
- button
- javascript
- yml
- jenv
- custom hooks
- 스크롤
- useMemo
- React Hooks
- yaml
- Pressable
- useState
- 리액트
- CORS
- withcredentials
- 상태관리
- React Native
- css
- useRef
- jdk
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |