0

我有以下代码,但我的 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
      );
    });
}

如何找出为什么护照没有调用身份验证器回调策略?

4

1 回答 1

2

我知道这个问题是关于 javascript 的,尽管我来这里是为了在TSeD.io框架中寻找 Typescript 的答案,其中同样没有触发 passport-jwt 策略。

对我来说,答案是(request, response)需要在Passport.Authenticate()调用中传递,当它被用作 Express 端点中的中间件时不需要这样做。像login这样按照https://tsed.io/tutorials/passport.html#local-strategysignup

.authenticate()我意识到,只要在快速端点之外进行呼叫,这就是必要的。例如也在https://medium.com/front-end-hacking/learn-using-jwt-with-passport-authentication-9761539c4314中。原因是因为在快速端点中调用的中间件将自动被传递(request, respone)

@Controller("/passport")
export class PassportCtrl {

  @Post("/login")
  async login(@Required() @BodyParams("email") email: string,
              @Required() @BodyParams("password") password: string,
              @Req() request: Express.Request,
              @Res() response: Express.Response) {


      return new Promise<IUser>((resolve, reject) => {
          Passport
              .authenticate("login", (err, user: IUser) => {
                  if (err) {
                      reject(err);
                  }

                  request.logIn(user, (err) => {

                      if (err) {
                          reject(err);
                      } else {
                          resolve(user);
                      }
                  });

              })(request, response, () => {

              });
      });
  }
}
于 2018-12-11T22:05:47.040 回答