Moon Work

[CORS] Cors를 처리해도 Cors 에러가 나는 경우(with Credentials) 본문

에러처리

[CORS] Cors를 처리해도 Cors 에러가 나는 경우(with Credentials)

moonkey 2022. 12. 28. 11:59

나는 cors가 싫다

끝나지 않는 Cors 에러

서버에 대한 개념도 모를 때 부터 Cors는 나를 괴롭게 하였지만 이렇게 가끔씩 나타나는 이 에러는 등장만으로도 속에서 불이 나곤한다. jwt 토큰을 통한 XSS와 CSRF 공격 방어를 공부하는데 이 녀석을 또 만났는데 cors()를 적용해도 에러가 발생하는 이유를 정리해본다.

 

Cors Error

 

에러 코드

Client

axios.defaults.withCredentials = true
axios.post('http://localhost:8080/login', data)
	.then(response => ...)
	.catch(error => ...)

Server

...
const app = express();
const server = http.createServer(app);
const PORT = 8080;

app.use(cors({
	origin: 'http://localhost:3000'
}))
...

 

 

문제점

client에서 axios.defaults.withCredentials를 설정해주었다. 이는 client에 있는 쿠키 정보를 server와 공유하기 위함인데 이를 위해서는 client와 server에서 모두 credential에 대한 허용을 해주어야 통신이 가능하다. 따라서 위에서 생긴 에러는 client에서만 Credential에 대해 허용을 해주고 server에서는 허용을 하지 않았기 때문에 발생한 에러이다.

 

 

해결

위와 같은 경우에는 cors의 credential option을 설정해줌으로 해결가능하다.

/*
app.use(cors({
    origin: "http://localhost:3000"
}))
*/
app.use(cors({
    origin: "http://localhost:3000",
    credentials: true,
}))

 

 

추가: Credential이란

Credential이란 쿠키, Authorization 인증 헤더, TLS client certificated를 포함하는 자격 인증 정보이다. 기본적으로 쿠키는 이 credentioal이 설정되어 있지 않는 한 이런 인증 정보를 포함하여 요청하지 않게 되어 있다. 따라서 이것을 설정해 준다는 것이 쿠키를 서버와 공유한다는 것을 의미한다. 

 

Credential 설정: Client

//방법1
axios.defaults.withCredentials = true

//방법2
axios.post('http://localhost:8080/login', 
	data,
	{withCredentials: true}
)

//방법3
fetch('http://localhost:8080/login', {
	method: "POST"
	credentials: "include"
})

 

Credential 설정: Server

//방법1
const httpServer = http.createServer(function(req, res)=> {
	response.setHeader('Access-Control-Allow-origin', '*')
	response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
    response.setHeader('Access-Control-Allow-Credentials', 'true')
})

//방법2

axios.use(cors({
	origin: '*'
	credentil: 'true'
}))

 

 

참조

https://inpa.tistory.com/entry/AXIOS-%F0%9F%93%9A-CORS-%EC%BF%A0%ED%82%A4-%EC%A0%84%EC%86%A1withCredentials-%EC%98%B5%EC%85%98