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

发布于 2022-09-07 12:06:17 字数 3261 浏览 19 评论 0

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代码戳这里

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忘年祭陌 2022-09-14 12:06:17

解决了,因为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
}))

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文