Passport-Discord登录后Cookie同时存储在两个本地端口的问题
问题
我正在使用PassportJS及passport-discord实现Discord OAuth登录,目前流程无异常,但遇到一个问题:
authRouter.get('/discord', passport.authenticate('discord', { session: false })) authRouter.get('/discord/callback', passport.authenticate('discord', { session: false }), (req, res) => { const token = jwt.sign(req.user , 'SECRET') res.cookie('token', token, { httpOnly: true, maxAge: 60000 }) res.redirect(`http://localhost:3000`) })
重定向到主站localhost:3000后,Cookie正常存储,但localhost:3001也存储了相同Cookie。我已使用cookie-parser,且严格遵循官方文档实现,请问这是预期情况吗?是否存在逻辑或安全隐患?
Passport-Discord配置代码:
var DiscordStrategy = require('passport-discord').Strategy; var scopes = ['identify', 'email', 'guilds', 'guilds.join']; passport.use(new DiscordStrategy({ clientID: 'id', clientSecret: 'secret', callbackURL: 'callbackURL', scope: scopes }, function(accessToken, refreshToken, profile, cb) { return cb(null, profile) }));
回答
这不是预期情况,问题根源是设置Cookie时未指定
domain属性。浏览器默认会将Cookie绑定到当前请求的域名(即你的认证服务所在的localhost:3001),而localhost属于特殊顶级域,浏览器会把同属localhost的不同端口视为同一域下的站点,导致Cookie在localhost的所有端口间共享。存在明确的安全隐患:如果localhost:3001是认证服务、localhost:3000是前端站点,那么其他运行在localhost其他端口的恶意服务也能获取到包含用户身份信息的JWT Token,可能引发身份伪造、敏感信息泄露等风险。
解决方案:设置Cookie时明确指定
domain、path属性,同时建议添加sameSite属性增强安全性:res.cookie('token', token, { httpOnly: true, maxAge: 60000, domain: 'localhost', path: '/', sameSite: 'Strict' // 防范CSRF攻击 })若希望Cookie仅在localhost:3000生效,由于localhost端口无法通过domain直接区分,建议开发环境使用不同子域名(如app.localhost和auth.localhost),配合hosts文件映射到127.0.0.1,这样就能通过domain精准控制Cookie的生效范围。
内容的提问来源于stack exchange,提问作者user19686218

