javascript - 如何使用 Passport 对我的端点进行身份验证?

标签 javascript node.js passport.js session-cookies

我已经使用 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/

相关文章:

javascript - 将选择值传递给另一个选择标签

javascript - three.js 中的碰撞墙

node.js - 为什么我的代理语句无法正常工作?

javascript - post API 中的重定向错误

reactjs - 如何在 react 组件中存储用户配置文件信息并全局访问它

javascript - Webpack:我们如何*有条件地*使用插件?

javascript - js 方法失败(抛出异常?),哪个 Firebug 不报告

javascript - 附加不同 Promise 链时 JavaScript Promise 的执行顺序

node.js - 使用 WebRTC.io 和 NodeJS 到达时连接到房间

javascript - Strongloop Passport.js 身份验证 - "Failed to obtain access token"