Egg set-cookie 与 Axios HttpOnly
Opened this issue · 2 comments
xiaotiandada commented
参考文章
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
- https://eggjs.org/zh-cn/core/cookie-and-session.html
- mqyqingfeng/Blog#157
- eggjs/egg#2721
- https://github.com/eggjs/egg/blob/master/config/config.default.js#L57
- https://eggjs.org/en/tutorials/proxy.html#mobileAside
代码都在这儿:https://github.com/xiaotiandada/cli-ant-temp
环境
前后分离项目set-cookie
Axios 配置
const client = axios.create({
baseURL: process.env.VUE_APP_API,
timeout: 1000 * 30,
headers: {
},
withCredentials: true,
})
需要设置withCredentials: true
axios默认是发送请求的时候不会带上cookie的
Egg 配置
利用 cors 跨域
// ...
const domainWhiteList = [ 'http://localhost:8080', 'http://127.0.0.1:8080' ];
config.security = {
domainWhiteList,
csrf: {
enable: false,
},
};
config.cors = {
origin: ctx => {
if (domainWhiteList.includes(ctx.request.header.origin)) {
return ctx.request.header.origin;
}
},
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
credentials: true,
};
// ...
Egg get
public async add() {
const ctx = this.ctx;
let count: any = ctx.cookies.get('count');
console.log('count', count);
console.log('token', ctx.cookies.get('access-token'));
count = count ? Number(count) : 0;
const countCookie: any = ++count;
ctx.cookies.set('count', countCookie, {
sameSite: 'none',
});
ctx.body = count;
}
Egg post
public async signIn() {
const { ctx } = this;
const { account, password } = ctx.request.body;
const payload = {
account,
password,
};
const secret = 'xxx';
const token = jwt.encode(payload, secret);
ctx.cookies.set('access-token', token, {
sameSite: 'none',
maxAge: ms('7d'),
});
ctx.body = {
data: token,
};
}
问题
部署到线上需要开启 sameSite: 'none'
, sameSite 需要开启 secure: true
ctx.cookies.set('access-token', accessToken, {
sameSite: 'none',
secure: true,
maxAge: ms('7d'),
});
HTTP 接口不支持 SameSite=none
如果你想加 SameSite=none 属性,那么该 Cookie 就必须同时加上 Secure 属性,表示只有在 HTTPS 协议下该 Cookie 才会被发送。
实际部署到线上会报错 Cannot send secure cookie over unencrypted connection
解决方案
i3web commented
总结:
需要在nginx这样设置
server {
server_name a.b.com;
proxy_set_header X-Forwarded-Proto $scheme;
}
在eggjs的config中这样设置
config.proxy=true;
wenshan commented
同样的问题,解决不了...