首页 > 解决方案 > 如何使用护照对我的端点进行身份验证?

问题描述

我已经使用 mongo db 设置了 spotify 护照策略来保存用户配置文件、访问和刷新令牌。但是除了最初的身份验证路由和回调 url 之外,我是否需要将 passport.authenticate 作为回调传递给每个路由?或者我应该有一个自定义中间件来检查 cookie-session 模块是否仍然有 req.user 请求?我认为这是两种可能性。哪个是正确的?我知道在 cookie 方面,它最终会过期,需要再次调用 /auth 路由。

我制作了一个中间件函数来检查请求对象的用户属性。但我不确定如何测试它。也许减少 cookie 过期时间并检查 req.user 是否为假。

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
});
 }

标签: javascriptnode.jspassport.jssession-cookies

解决方案


您可以创建一个middleware将检查用户是否存在的内容authenticated,并将其添加middleware到您的routes.

PassportdeserializeUser每次调用请求时都会运行,并将经过身份验证的用户存储在req.user. 将middleware检查是否req.user存在,如果它退出则意味着用户是logged inand authenticated,并且可以允许请求继续进行。

您不需要对passport.authenticate('spotify')每个请求都使用它,您只需要在login( 或registration) 时使用它。

中间件可以这样添加:

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
});

我希望这对你有用。


推荐阅读