我正在使用express.js和passport-jwt,并且正在创建一个中间件,该中间件在每个API调用中检查用户,然后分配给用户。因此,每次我登录req.user
时,我都会获得有关用户的详细信息,并且可以正常工作。然后,如果我想注销该用户,我使用了req.logout()
,req.logOut()
,req.destroy()
,甚至我尝试将null
分配给req.user
,但它仍然登录请我帮忙。
护照配置
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
var passport = require('passport')
const User = require('../schema/userSchema')
var opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'social';
exports.Strategy = new JwtStrategy(opts, async (jwt_payload, done) => {
const user = await User.findOne({ _id: jwt_payload.id})
if (!user) {
return done({error:'error'}, false);
}
if (user) {
return done(null, user);
} else {
return done({error:'error'}, false);
}
})
exports.auth = passport.authenticate('jwt', { session: false })
server.js
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
var cors = require('cors')
var passport = require('passport')
var passportmethods = require('./methods/passport')
var postRoute = require('./router/posts')
var authRoute = require('./router/auth')
var friendRoute = require('./router/friend')
var verif = require('./router/user')
app.use('/uploads',express.static('../backend Social/uploads'))
app.use(cors())
app.use(bodyParser.json())
passport.use(passportmethods.Strategy)
app.use('/auth',authRoute)
app.use('/post',passportmethods.auth,postRoute)
app.use('/friend',passportmethods.auth,friendRoute)
app.use('/user',passportmethods.auth,verif)
app.listen(3000,()=>console.log('server on !'))
登录和注销
const express = require('express');
const router = express.Router();
const logout = require('express-passport-logout');
const User = require('../schema/userSchema')
router.get('/isloggedin', (req, res, next) => {
if (req.user) res.send(req.user)
else res.send({ error: 'error' })
})
router.get('/logout',async (req, res, next) => {
await User.updateOne({_id:req.user._id},{$set :{connected : false}})
console.log(req.user._id)
req.logOut()
if(req.user)res.send(req.user._id)
else res.send('logged out')
})
module.exports = router;
答案 0 :(得分:0)
据我所知,您不应该从服务器端实现注销。让您的客户处理注销,因为我们不在服务器中的任何位置存储令牌。因此,要从客户端注销,只需删除令牌。另外,除非必须这样做,否则不要将令牌存储在数据库中;如果要这样做,则应像密码一样对令牌进行哈希处理。如果数据库中存在安全漏洞,将令牌存储在数据库中是有风险的,入侵者将拥有一切权力。
答案 1 :(得分:0)
首先-您将端点用作中间件。我会尝试没有“下一个”。然后-我将尝试使用req.logout()而不是req.logOut()。还可以使用try-catch块包装您的await呼叫。架构承诺可能存在问题。