我已经使用 mongo 数据库设置了 Spotify Passport 策略来保存用户配置文件、访问和刷新 token 。但除了初始身份验证路由和回调 url 之外,我是否需要将 Passport.authenticate 作为回调传递给每个路由?或者我应该有一个自定义中间件来检查 cookie-session 模块是否仍然有 req.user 请求?我认为这是两种可能性。哪一个是正确的?我知道在 cookie 方面,它最终会过期,并且需要再次调用/auth 路由。
我制作了一个中间件函数来检查请求对象的用户属性。但我不确定如何测试它。也许减少 cookie 过期时间并检查 req.user 是否为 false。
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id)
.then((user) => {
done(null, user);
});
});
passport.use(new SpotifyStrategy({
clientID: keys.spotifyClientID,
clientSecret: keys.spotifyClientSecret,
callbackURL: '/auth/spotify/callback',
proxy: true
}, async (accessToken, refreshToken, profile, done) => {
const spotifyId = profile.id
const name = profile.displayName
const email = profile.emails[0].value
const existingUser = await User.findOne({ spotifyId: profile.id });
if (existingUser) {
return done(null, existingUser);
}
const user = await new User({ spotifyId, name, accessToken, refreshToken}).save();
done(null, user);
}));
Check the cookie middleware:
module.exports = isAuthenticated = (req, res, next) => {
if (req.user) {
return next();
}
return res.redirect('/auth/spotify');
}
Example route:
module.exports = (app) => {
app.get('/api/spotify/playlists', passport.authenticate('spotify'),
(req, res) => {
console.log('got here')
console.log(req.user);
//return playlists
});
}
最佳答案
您可以创建一个中间件
,它将检查用户是否经过身份验证
,并将该中间件
添加到您的路由中
.
Passport 每次调用请求时都会运行 deserializeUser
,并将经过身份验证的用户存储在 req.user
中。 中间件
将检查req.user
是否存在,如果存在,则意味着用户已登录
并且已通过身份验证
,并且可以允许请求继续进行。
您不需要在每个请求中使用passport.authenticate('spotify')
,您只需在登录
(或注册
)。
中间件可以这样添加:
function isAuthenticated(req, res, next) {
if (req.user) {
next();
} else {
res.redirect('/login');
}
}
app.get('/api/spotify/playlists', isAuthenticated,
(req, res) => {
console.log('got here')
console.log(req.user);
//return playlists
});
我希望这对你有用。
关于javascript - 如何使用 Passport 对我的端点进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55345261/