javascript - 如何使用护照对我的端点进行身份验证?
问题描述
我已经使用 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
});
}
解决方案
您可以创建一个middleware
将检查用户是否存在的内容authenticated
,并将其添加middleware
到您的routes
.
PassportdeserializeUser
每次调用请求时都会运行,并将经过身份验证的用户存储在req.user
. 将middleware
检查是否req.user
存在,如果它退出则意味着用户是logged in
and 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
});
我希望这对你有用。
推荐阅读
- postgresql - 使用递归 cte 时 Postgres '输入结束时的语法错误'
- mysql - RAILS - 连接三个表以根据计数获取关联记录
- python - 难以在不同列中的 csv 文件中写入数据
- java - 我应该如何保存和加载具有所有属性的 JTable?
- azure-active-directory - 在 AzureAD SCIM 中强制发送删除请求
- reactjs - 如何正确编写 Redux ReactJS 模态组件?
- auth0 - 将 auth0 与 react-native 集成
- android-studio - Android Studio Designer Preview 在实现 Material Components 库后变黑了
- excel - Power Query M 语言语法错误 Expression.Error
- python - 打开 Ai 的 CLIP 和图像数据库