如何使用护照对我的端点进行身份验证?

How to authenticate against my end points with passport?

我已经使用 mongo 数据库设置了 spotify 护照策略来保存用户配置文件、访问和刷新令牌。但是除了最初的 auth 路由和回调 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
});
 }

您可以创建一个 middleware 来检查用户是否 authenticated,然后将 middleware 添加到您的 routes.

Passport 在每次调用请求时运行 deserializeUser,并将经过身份验证的用户存储在 req.user 中。 middleware会检查req.user是否存在,如果存在则说明用户是logged inauthenticated,可以允许请求继续。

您不需要对每个请求都使用 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
});

我希望这对你有用。