egg.js + vue时,post请求出现 csrf 的疑问

egg.js config.default.js 配置:

  // csrf
  config.security = {
    csrf: {
      //   enable: false
    },
    domainWhiteList: ['http://localhost:8080', 'http://192.168.1.106:8080']
  }
  config.cors = {
    origin: '*',
    allowMethods: 'GET, HEAD, PUT, POST, DELETE, PATCH'
  }

通过 controller 把 csrf 传递给vue

  async setCsrf() {
    const { ctx } = this
    ctx.body = {
      status: 200,
      csrf: ctx.csrf
    }
  }

Vue 中的配置

  mounted () {
    axios.get('http://127.0.0.1:7001/api/v3/login-csrf').then(res => {
      console.log(res.data.csrf);
      sessionStorage.setItem('csrfToken', res.data.csrf)

    })
  },
  methods: {
    submitForm () {
      axios({
        url: 'http://127.0.0.1:7001/api/v3/admin',
        method: 'post',
        data: {
          _csrf: sessionStorage.getItem('csrfToken'),
          username: this.ruleForm.username,
          password: this.ruleForm.password
        },
        headers: {
          'x-csrf-token': sessionStorage.getItem('csrfToken')
        }
      })
        .then(respanse => {
          console.log(respanse.data);
        })
    },
  }

这样配置每次post是都会出现“ 安全威胁csrf的防范” 的提示

response headers 中已经有 x-csrf-token

暂时不能关闭 csrf 功能,因为项目后台是采用vue,而前台显示是用egg渲染模板的,所以要保留 csrf 功能;

阅读 4.1k
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题