第三方登陆后,无法将用户信息存到session 中
发布于 6 年前 作者 hellomrbigshot 3198 次浏览 来自 问答

做博客的时候在登录界面搞了个 github 登录,希望在 github 接口调用结束,若是有用户已绑定该 github 账号就直接登录。于是在查询该用户存在成功后会将用户信息存到 session 中(express-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代码戳这里

4 回复

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

@hellomrbigshot secure这个是给https用的,你用http吧?

@zy445566 对滴,用的 http,要将 secure 设置为 false 才能生效

get到一个知识点

回到顶部