Cannot contain cookie in request header :(
withCredentials
Problem
Webview์์ Server๋ก ์์ฒญ์ ๋ณด๋ผ ๋, HTTP header์ Cookie๊ฐ์ด ํจ๊ป ์ ๋ฌ๋์ง ์๋๋ค. Cookie storage์๋ ์ ๋ค์ด์ ์๋ค.
Situation
- ์ํฉ 1. ๋๋ฉ์ธ์ด ๋ค๋ฅด๋ค.
- ์๋ฒ์ ๋๋ฉ์ธ: api.test.me
- request๋ฅผ ๋ณด๋ด๋ ํด๋ผ์ด์ธํธ์ ๋๋ฉ์ธ: test.me
- no nginx, no proxy
- ์ํฉ 2. request header์ ์ง์ ์ ์ผ๋ก cookie ๊ฐ์ ์ธํ
ํ ์ ์๋ค.
- HttpOnly ์ฟ ํค์๊ธฐ ๋๋ฌธ์, document.cookie์ ์ ๊ทผํ ์ ์๋ค.
- ์ํฉ 3. ์๋ฒ์์ Set-Cookie๋ฅผ ํด์ฃผ๊ธฐ ์ ์ request header์ cookie๋ฅผ ์ธํ
ํด์ผ ํ๋ค.
- App์์ ์ฟ ํค๋ฅผ ์ฃผ์ ํ์ฌ Webview๋ฅผ ๋์์ค๋ค.
- Webview์์ ๋ฐ์ํ๋ request header์๋ cookie๊ฐ ์ค์ ๋์ด์ผ ํ๋ค.
Solution
axiosConfig.withCredentials = true
or
fetch({
credentials: 'include'
})
reference์ ์ฒจ๋ถํ mdn ๋ฌธ์์์ ๋ค์๊ณผ ๊ฐ์ด ๋์จ๋ค.
Note: XMLHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request, regardless of Access-Control- header values.
๋๋ฒ์งธ๋ก ์ฒจ๋ถํ HTML5Rock์ ๋ธ๋ก๊ทธ ๊ธ์๋ ๋ค์๊ณผ ๊ฐ์ด ๋์จ๋ค.
Standard CORS requests do not send or set any cookies by default. In order to include cookies as part of the request, you need to set the XMLHttpRequestโs .withCredentials property to true:
์น์๋ชป ์ธ์ฆํ๋ฉฐ ๊ฒธ์ํด์ง๋ ๋ ์ด์๋ค.
Knowledge
Cookie?
HTTP ์์ฒญ์ ์์ ํ ๋, ์๋ฒ๋ ์๋ต๊ณผ ํจ๊ป Set-Cookie ํค๋๋ฅผ ์ ์กํ ์ ์๋ค. ์ฟ ํค๋ ๋ณดํต ๋ธ๋ผ์ฐ์ ์ ์ํด ์ ์ฅ๋๋ฉฐ, ๊ทธ ํ ์ฟ ํค๋ ๊ฐ์ ์๋ฒ์ ์ํด ๋ง๋ค์ด์ง ์์ฒญ(Request)๋ค์ Cookie HTTP ํค๋์์ ํฌํจ๋์ด ์ ์ก๋๋ค.
์ฟ ํค๋...
- ๋๊ฐ ์น ์ ํ๋ฆฌ์ผ์ด์ ์์ ์ฌ์ฉ์์ ๊ทธ๋ค์ ์ธ์ฆ๋ ์ธ์ ์ ์๋ณํ๊ธฐ ์ํด ์ฌ์ฉ๋๊ณค ํ๋ค.
- ๋ ์์ฒญ์ด ๋์ผํ ๋ธ๋ผ์ฐ์ ์์ ๋ค์ด์๋์ง ์๋์ง๋ฅผ ํ๋จํ ๋ ์ฃผ๋ก ์ฌ์ฉํ๋ค.
Set-Cookie: <cookie-name>=<cookie-value>
in Node.js
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
์ด๋ ๊ฒ ์์ฑ๋๋ ์ผ๋ฐ์ ์ธ ์ฟ ํค๋ฅผ ์ฐ๋ฆฌ๋ ์ธ์ ์ฟ ํค๋ผ๊ณ ๋ถ๋ฅธ๋ค. ์ด๋ Chrome Devtools์ ์๋ Storage ํญ์ Cookie์์ ํ์ธํ ์ ์๋ค.
Persistent Cookie
๋ณดํต ์ฟ ํค๋ ํด๋ผ์ด์ธํธ๊ฐ ์ข ๋ฃ๋๋ฉด ์ญ์ ๋๋ค. ์น ๋ธ๋ผ์ฐ์ ๋ ์ธ์ ์ ๋ณต๊ตฌ์ํฌ ์ ์์ผ๋ฉฐ ์ด ๋ ์ฟ ํค๋ฅผ ํจ๊ป ๋ณต๊ตฌ์ํฌ ์ ์์ผ๋ฉฐ ์ด ๋ ๋ณต๊ตฌ๋๋ ์ฟ ํค๋ฅผ ์์์ ์ธ ์ฟ ํค๋ผ๊ณ ํ๋ค. Expires๋ Max-Age๋ฅผ ๋ช ์ํ์ง ์์ผ๋ฉด ์์์ ์ธ ์ฟ ํค๊ฐ ๋๋ฉฐ ์ด ๋ ์ต์ ์ ์ธ์ ์ฟ ํค๋ฅผ ์์์ ์ธ ์ฟ ํค๋ก ๋ฐ๊ฟ์ค๋ค.
Secure, HttpOnly Cookie
Cookie์๋ HTTPS ํ๊ฒฝ์์๋ง Request header์ ํฌํจ๋ ์ ์๋๋ก ํ๋ Secure option์ด ์๋ค. HttpOnly ์ต์
์ document.cookie ๋ฅผ ํตํด ์ ๊ทผํ ์ ์๋ค.
References
- https://developer.mozilla.org/ko/docs/Web/API/XMLHttpRequest/withCredentials
- https://www.html5rocks.com/en/tutorials/cors/