我已经为JWT初始化了策略:
const jwtStrategyOptions = {
jwtFromRequest: ExtractJwt.fromHeader('x-access-token'),
secretOrKey: 'publicKey',
}
passport.use(
new JwtStrategy(
jwtStrategyOptions,
(payload, done) => {
MySQL.Users.readOne(['id'], { id: payload.userId })
.fork(
error => {console.log(error)
done(error)},
user => {
console.log(user)
done(null, user)}
)
}
)
)
和中间件:
const isAuthenticated: RequestHandler = (req, res, next) => {
passport.authenticate(
'jwt',
{ session: false, failWithError: true },
(error, user) => {
//error is null when I pass empty payload
if (error) {
return next(error)
}
req.user = user
return next()
}
)(req, res, next)
}
但是当我通过空的或无效的令牌护照时,只需通过
(payload, done) => {
MySQL.Users.readOne(['id'], { id: payload.userId })
.fork(
error => {console.log(error)
done(error)},
user => {
console.log(user)
done(null, user)}
)
}
步骤和代码执行next()
功能。
我能以某种方式检测到有效载荷无效或为空吗?
答案 0 :(得分:1)
我不太确定MySQL的调用返回类型,但是如果没有与ID相匹配的内容,是否会引发错误?
private static void setHandlersLevel(Level lvl) {
for (Handler h : logger.getHandlers()) {
h.setLevel(Level.FINE);
}
}
如果它没有引发错误,但返回空值或空值,则需要在“成功”回调函数中对其进行检查,因为在这种情况下,它将使用空值调用private static void setAllHandlersLevel(Level lvl) {
LogManager lm = LogManager.getLogManager();
synchronized (lm) {
Enumeration<String> e = lm.getLoggerNames();
while (e.hasMoreElements()) {
Logger l = lm.getLogger(e.nextElement());
if (l != null) {
for (Handler h : l.getHandlers()) {
h.setLevel(lvl);
}
}
}
}
}
。
根据您的评论,这可能会对我用来检查令牌过期错误的某些代码有所帮助:
(payload, done) => {
MySQL.Users.readOne(['id'], { id: payload.userId })
.fork(
error => {console.log(error)
done(error)},
user => {
console.log(user)
done(null, user)}
)
}