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
了
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决了,因为github登录成功后是 http 方式跳转过去的,所以 express-session 需要设置下 secure: false
怪我没有仔细看文档=。=