npm install cookie-parser
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// cookie-parser 미들웨어 추가
app.use(cookieParser());
res.cookie를 통해 만들 수 있으며 res.cookie(key, value, option)의 형태로 사용한다.
Option
- maxAge : 만료 시간(밀리초 단위)
- expire : 만료 날짜
- path : 쿠키 경로(
/가 기본값)- domain : 도메인명 (
loaded가 기본값)- secure : https에서만 사용 허용
- httpOnly : 웹서버를 통해서만 쿠키 접근 허용
- signed : 쿠키에 대한 서명 지정
const cookieOptions = {
HttpOnly: true,
secure: true,
};
res.cookie("name", 'judyan', cookieOptions);
res.clearCookie를 사용하여 쿠키를 제거한다.
key, value, option 모두 일치해야 한다.
res.clearCookie("name", 'judyan', {
HttpOnly: true,
secure: true,
};);
cookieParser()의 첫 번째 인수로 비밀 키를 넣어 줄 수 있다. signed:true옵션을 포함하면 서명된 쿠키를 생성한다.
res.cookie('name', 'judyan', { signed:true })
서명된 쿠키는 req.signedCookies객체를 통해 접근할 수 있다
app.use(cookieParser(process.env.COOKIE_SECRET));
app.get('/', (req, res) => {
req.signedCookies // 서명 된 쿠키 데이터
});
프론트에서 요청을 보낼 때 withCredentials설정
withCredentials: 해당 요청에 사용되는 쿠키 정보를 포함시킬지 여부를 나타내는 옵션- 웹 브라우저는 보안 상의 이유로 다른 도메인으로 요청을 보낼 때 쿠키를 포함하지 않기 때문에
withCredentials옵션을true로 설정해야 한다
// axios
axios.get(url, {withCredentials:true});
// fetch
fetch(url, {
credentials: 'include'
})
서버에서는 CORS설정을 해줘야 한다 -> CORS 허용참고
let corsOptions = {
origin: "http://localhost:9000",
credentials: true,
};
app.use(cors(corsOptions));
쿠키를 생성할 때 sameSite옵션을 none으로 해야한다
sameSite
쿠키는 기본적으로 동일 출처(Same Origin) 정책에 따라 동작하며, sameSite 속성을 사용하여 쿠키의 전송을 제한할 수 있다.
None: 항상 다른 도메인으로 전송될 수 있음. secure속성이 함께 설정되어 있어야 함Strict: 다른 도메인으로의 모든 요청에 대해 제한Lax: 기본값. 다른 도메인으로의 전송을 제한
// ...
res.cookie("refreshTkn", refreshToken, {
httpOnly: true,
sameSite: "none",
secure: true,
});