因此我尝试将passport-jwt与Sequelize模型一起使用,并将user.id解析为数据库中的现有模型。 结果完全不是我所期望的,它给了我一个"标题已经被发送"错误,表示护照-jwt已经发送了"未找到"到我的客户端(这只是一个带有标题的卷曲)
curl http://10.0.0.39/api/secure -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJrb21tZW50anMuY29tIiwiaWF0IjoxNTE3MTY1MDkzLCJleHAiOjE1NDg3MDEwOTMsImF1ZCI6Ind3dy5leGFtcGxlLmNvbSIsInN1YiI6IjEyMyJ9.s1r6jkqBGZ8cAYEWdsvRVjHNohj2-aYzo-S_TH_2gAI"
这方面的回应
Not Found
示例代码附在下面。调试日志表明代码实际上同时调用了" .then"条款和" .catch"子句。
我哪里弄错了?
import * as passportJwt from "passport-jwt"
import {config} from "../../config"
import {models} from "../../database"
import {logger} from "../../logger"
import { UserInterface, UserModel } from "../../models/user";
const jwtOptions: passportJwt.StrategyOptions = {
jwtFromRequest: passportJwt.ExtractJwt.fromAuthHeaderWithScheme("jwt"),
secretOrKey: config.jwt.secret,
issuer: config.jwt.issuer
};
let jwtStrategy = new passportJwt.Strategy(jwtOptions, async (payload,done)=>{
models.user.findById(parseInt(payload.sub)).then((user: UserInterface | null)=>{
if (user){
console.log("user found");
return done(null,user,payload);
} else {
console.log("user not found");
return done(null,false,payload);
}
}).catch((err)=>{
console.log("error");
console.log(err);
return done(err,false,null);
});
})
export {jwtStrategy}
调试日志如下所示:
info: Executing (default): SELECT "id", "username", "isPrimary", "notificationList", "subscriptionList", "moderationList", "siteList", "connections", "avatar", "createdAt", "updatedAt" FROM "users" AS "user" WHERE "user"."id" = 123; logging=function (msg) {
// build argument list (level, msg, ... [string interpolate], [{metadata}], [callback])
var args = [level].concat(Array.prototype.slice.call(arguments));
target.log.apply(target, args);
}, plain=true, raw=false, where="user"."id" = 123, rejectOnEmpty=false, hooks=true, attributes=[id, username, isPrimary, notificationList, subscriptionList, moderationList, siteList, connections, avatar, createdAt, updatedAt], tableNames=[users], type=SELECT, model=class extends Model {}
找不到用户 错误 {AssertionError [ERR_ASSERTION]:标题已发送 在Object.set状态[作为状态]
更新:尝试使用不同的版本,但使用Promise样式调用来代替sequelize,这里仍然存在同样的问题。
let jwtStrategy = new passportJwt.Strategy(jwtOptions, (payload,done)=>{
models.user.findOne({where: {id: parseInt(payload.sub)}}).then((result: UserInterface | null)=>{
if (result){
console.log("user found");
return done (null, result, payload);
} else {
console.log("user not found");
return done (null, false, "not found");
}
}).catch((err)=>{
console.log("error");
console.log(err);
return done(null, false, {message: err.message});
})
})