csrf 安全验证
- 请求出现invalid csrf token安全验证的报错
//方法一:在confit.default.js新增以下代码,表示关闭安全验证(不推荐)
config.security = {
csrf: {
enable: false,
},
};
//方法二: 在前端初始化界面的时候,让前端先get请求一个接口,后台返回一个秘钥给前端,让前端在t请求的时候放在headers请求头里,egg会自动去验证这个秘钥,验证成功才会成功请求。
//1、egg后台代码,get接口返回秘钥:
async interfacName() {
ctx.body = {
csrf:this.ctx.csrf
};
}
//2、前端带上秘钥请求:
axios.post('apis/add', data,{Í:{'x-csrf-token': headData}})
session 设置
//后端
config.cors = {
// origin: ctx => ctx.get('origin'),
domainWhiteList: ['http://127.0.0.1:9000', 'http://127.0.0.1:3000'],
credentials: true, //允许Cook可以跨域
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS'
};
// 在登录接口处设置session内容
let openId = new Date().getTime()
this.ctx.session.openId = openId
/*在其他接口处,通过中间件来判断是否找到对应cookie键的session是否有值**/
module.exports = options => {
return async function adminauth(ctx, next) {
//调试session时地址不能是localhost
console.log('session', ctx.session.openId)
if (ctx.session.openId) {
await next()
} else {
ctx.body = { data: '没有登录' }
}
}
}
//前端
axios.defaults.headers['Access-Control-Allow-Origin'] = '*'
axios.defaults.withCredentials = true
坑: 开发的时候,地址不能用localhost 不然获取不到session。必须用ip地址,用127.0.0.1代替