nodejs 第三方 github 登录后信息无法写入 session

github.js(用来github第三方登录)

router.get('/login', checkNotLogin, async (req, res, next) => {
    const dataStr = (new Date()).valueOf()
    //  重定向到认证接口,并配置参数
    let path = "https://github.com/login/oauth/authorize"
    path += '?client_id=' + config.client_id
    path += '&scope=' + config.scope
    path += '&state=' + dataStr
    // 转发到授权服务器
    res.redirect(path)
})
router.get('/oauth/callback', checkNotLogin, (req, res, next) => {
    const code = req.query.code;
    let path = 'https://github.com/login/oauth/access_token';
    const params = {
        client_id: config.client_id,
        client_secret: config.client_secret,
        code: code
    }
    fetch(path, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(params)
    })
    .then(result => {
        return result.text()
    }).then(body => {
        let access_token = body.split('&')[0].split('=')[1]
        return access_token
    }).then(token => {
        const url = ' https://api.github.com/user?access_token=' + token;
        fetch(url)
            .then(info => {
                return info.json();
            })
            .then(github_info => {
                UserModel.getUserByOauthInfo({ type: 'github', name: github_info.login }).then(user => {
                    if (user) {
                        // 已注册,获取登录信息后直接跳转到列表页
                        user = user.toObject()
                        delete user.password
                        req.session.user = JSON.parse(JSON.stringify(user))
                        res.redirect(`${config.main_url}?username=${user.username}`)
                    } else {
                        // 如果没有注册,就跳转到注册界面
                        res.redirect(`${config.register_url}?name=${github_info.login}&type=github&avatar_url=${github_info.avatar_url}&bio=${github_info.bio}`)
                    }
                })
                
            })

    })
})

如代码中所示,如果 github 账号已与现有账号关联,后端会直接

req.session.user = JSON.parse(JSON.stringify(user))
user 保存到 req.session

但是在登录之后,我在界面上做一些其他的操作,调用了其他的接口,接口中用到了监测是否登陆的中间件 check.js

    checkLogin (req, res, next) {
        if (!req.session.user) { // 登录超时 前端通过状态码 401 识别
            console.log(req.session.user)
            res.status(401).json({ code: 'error', data: '该用户未登录' })
            return false
        }
        next()
    },
    checkNotLogin (req, res, next) {
        if (req.session.user) {
            console.log(req.session.user)
            res.status(402).json({ code: 'error', data: '该用户已登录' })
            return false
        }
        next()
    }

当用 github 直接登录时中间件打印出来的 req.session.user 一直是 undefined
我不太明白,我觉得我登录的时候已经将 user 信息保存到 req.session

github.js代码链接戳这里
中间件check.js代码戳这里

阅读 2.8k
1 个回答

解决了,因为github登录成功后是 http 方式跳转过去的,所以 express-session 需要设置下 secure: false

app.use(session({
    secret: 'Stefanie Sun',
    store: sessionStore,
    resave: true, // 强制更新 session
    saveUninitialized: true,  // 
    cookie: { 
        maxAge: 3 * 3600 * 1000,  // 过期时
        secure: false // http 访问时 secure 为 false
  }, 
    rolling: true
}))

怪我没有仔细看文档=。=

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