未触发Passport JWT策略

时间:2018-04-01 13:15:14

标签: node.js passport.js passport-jwt

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

Server.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')}/`);     });

Routes.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
      );
    });
}

如何找出护照未调用身份验证器回调策略的原因?

1 个答案:

答案 0 :(得分:1)

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

对我来说,答案是(request, response)需要在Passport.Authenticate()调用中传递,当它在Express终结点中用作中间件时,不需要执行某些操作。像https://tsed.io/tutorials/passport.html#local-strategy上的loginsignup一样。

我意识到,只要在明确端点之外进行.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, () => {

              });
      });
  }
}