我有以下代码,但我的 passport-jwt 策略没有被触发:
Authenticator.js
import passport from "passport";
import passportJWT from "passport-jwt";
const ExtractJwt = passportJWT.ExtractJwt;
const JwtStrategy = passportJWT.Strategy;
export const set = app => {
const opts = {
secretOrKey: secret,
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()
};
let strategy = new JwtStrategy(opts, (payload, done) => {
console.log("Strategy called");
console.log(payload);
// Check user and company
let user = getUserById(payload);
if (!user) return done(new Error("User not found"), false);
let context = {
id: user.id,
username: user.username,
name: user.name
};
return done(null, context);
});
passport.use(strategy);
console.log("Initializing passport");
app.use(passport.initialize());
};
服务器.js
import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import * as routes from "./routes";
import * as authenticator from "./authenticator";
mongoose.Promise = global.Promise;
const app = express();
app.set("port", process.env.API_PORT || 3001);
app.disable("x-powered-by");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const mongoUri = process.env.MONGO_URI || "mongodb://localhost/db";
mongoose.connect(mongoUri);
authenticator.set(app);
routes.set(app);
app.listen(app.get('port'), () => {
console.log(`Find the server at: http://localhost:${app.get('port')}/`); });
路线.js:
import express from "express";
import passport from "passport";
import path from "path";
import appGraphQL from "graphql/src/graphql";
import * as authenticator from "./authenticator";
const router = express(router);
export const set = app => {
app.use(
"/graphql",
passport.authenticate("jwt", { session: false }),
appGraphQL()
);
};
从客户端获取:
function fetchQuery(operation, variables, cacheConfig, uploadables) {
const token = sessionStorage.getItem('jwtToken');
return fetch(SERVER, {
method: 'POST',
headers: {
Authorization: 'Bearer ' + token,
Accept: 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify({
query: operation.text,
variables
})
})
.then(response => {
if (response.status === 401)
throw new Error('Error401:Unauthorized');
else return response.json();
})
.catch(error => {
throw new Error(
'(environment): Error while fetching server data. ' + error
);
});
}
如何找出为什么护照没有调用身份验证器回调策略?