xiaotiandada/blog

Egg set-cookie 与 Axios HttpOnly

Opened this issue · 2 comments

参考文章

代码都在这儿: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,
    };
  }

image

问题

部署到线上需要开启 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

解决方案

image

应该设置Nginx等(caddy)可以解决问题,但是我这里是设置Egg config的 proxy 解决这个问题

i3web commented

总结:
需要在nginx这样设置

server {
  server_name a.b.com;
  proxy_set_header X-Forwarded-Proto $scheme;
}

在eggjs的config中这样设置
config.proxy=true;

同样的问题,解决不了...