egg中间件权限认证(cookie的跨域访问)

本文详细介绍了如何处理前端与后端跨域携带Cookie的问题,包括前端Axios的配置,设置`withCredentials`属性,以及后端设置响应头以允许跨域并设置Cookie。同时,还展示了如何在Egg.js中进行中间件验证,确保只有携带正确Cookie的请求才能访问受保护的API。

解决跨域携带cookie的问题

  • 前端设置
//在每次请求的时候在加一个withCredential:true
axios({
    url:`${baseURL}/addArticle`,
    method:"POST",
    //一定要设置下面这个headers才可以跨域携带
    headers:{
    'Access-Control-Allow-Origin':'http://localhost:8080/'
    },
    withCredentials:true,
})


//在login的时候也要加withCredential:true
axios({
    url:`${baseURL}/login`,
    method:"post",
    withCredentials:true,
    data:{
        userName:userName.value,
        userPassword:userPassword.value
    },
})
  • 后端设置

set-cookie

ctx.cookies.set("token", token, {
    httpOnly: true, // 默认就是 true
    path:'/',
    maxAge: 0.5 * 3600 * 1000,//有效时间 30分钟
    signed:false,
    encrypt:false//对cookie加密
    });

设置允许跨域访问

config.cors = {
    origin: ctx => ctx.get('origin'),
    credentials: true,  //允许Cookie可以跨域
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS'
};
  • egg.js设置中间件来进行权限验证
//在app文件夹中新建一个middleware文件夹,简历一个adminauth.js文件
module.exports = options =>{
    return async function adminauth(ctx,next){
        //判断传上来的cookie中的token和session中的token一样不
        if(ctx.session.token==ctx.request.header.cookie.split(';')[0].split('=')[1]){
            await next()
        }else{
            ctx.body={data:'没有登录'}
        }
    }
}

//然后在router.js中使用中间件
var adminauth = app.middleware.adminauth()
//这样就有了权限验证
router.post('/addArticle',adminauth,controller.home.addArticle)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值