ExpressJS - JWT和Passport实施

时间:2017-09-27 13:03:26

标签: express authentication token jwt passport.js

我目前正在尝试学习JWT和Passport for ExpressJS,但我似乎无法理解Passport如何运作。

这是我最初在ExpressJS应用程序中所做的事情。

/api/login POST API

  • 接受用户名和密码
  • /api/login然后使用用户名和密码作为有效负载
  • 创建一个JWT
  • 然后令牌响应客户端

我认为我的/api/login API模拟了JWT一次硬认证的一般概念并用令牌进行响应。

另一方面,

/api/test GET API

  • 只有经过身份验证的用户才能访问
  • 只需返回" Hello World!"

问题是什么?

  • 我的代码似乎没有验证令牌(我尝试将令牌放入Authenticate标头。
  • 我的请求中应该在请求/api/login时是否包含/api/test返回的令牌?

现在我的实际代码:

app.js

var express = require("express");
var bodyParser = require("body-parser");
var jwt = require("jsonwebtoken");
var passport = require("passport");
var LocalStrategy = require('passport-local').Strategy;
var mySecret = "mySecret";
var app = express();
var port = process.env.PORT || 3000;

app.use(bodyParser.json());

passport.use(new LocalStrategy(
    function (token, done) {
        var credentials = jwt.verify(token, mySecret);
        if (credentials.username == "test" && credentials.password == "test") {
            return done(null, credentials);
        } else {
            return done(null, false);
        }
    }
));

app.use(passport.initialize());

app.post("/api/login", function (request, response) {
    var user = {
        "username": request.body.username,
        "password": request.body.password
    };
    response.send(jwt.sign(user, "mySecret"));
});

app.get("/api/test", passport.authenticate("local", {
    "session": false
}), function (request, response) {
    response.send("Hello World!");
});

app.listen(port, function () {
    console.log("Listening on port: " + port);
});

1 个答案:

答案 0 :(得分:1)

您还需要配置 jwtStratagy 以对用户进行身份验证。 这是工作示例: -

const express = require("express");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
console.log(jwt.verify);
const passport = require("passport"),
  LocalStrategy = require("passport-local").Strategy;
const cors = require("cors");
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(passport.initialize());
var secret = '11210646';
var JwtStrategy = require('passport-jwt').Strategy,
  ExtractJwt = require('passport-jwt').ExtractJwt;
passport.use(new LocalStrategy({
    usernameField: 'username',
    passwordField: 'password',
    passReqToCallback: true
  },
  function(req, username, password, done) {
    console.log('ohh', username, password);
    let err = null;
    if (err) { return done(err); }
    if (username != 'abhi') {
      return done(null, false, { message: 'Incorrect username.' });
    }
    if (password != 'pass') {
      return done(null, false, { message: 'Incorrect password.' });
    }
    return done(null, username);

  }
));
app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    console.log(err, user, info);
    if (err) { return next(err); }
    if (!user) { res.send({ "status": info.message }); }
    res.send({ "status": user });
  })(req, res, next);
});
var opts = {
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: secret,
  issuer: 'jonu',
  audience: 'jonu bhai',
  passReqToCallback: false
};
app.post('/me2', function(req, res, next) {
  passport.authenticate('jwt', { session: false }, function(err,user, info) {
    if (err) { return next(err); }
    if (!user) { res.send({ "status": info.message }); }
    res.send({ "status": user });
  })(req, res, next);

});
//jwt

passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
  let err = null;
  if (err) {
    return done(err, false);
  }
  if (jwt_payload) {
    return done(null, jwt_payload);
  }
  else {
    return done(null, false);
    // or you could create a new account
  }

}));


app.post('/signup', (req, res) => {

  let token = jwt.sign({
      user: {
        id: "idididid",
        name: "Abhishek Singh",
        username: "abhishek11210646"
      }
    },
    secret, {
      algorithm: 'HS256',
      expiresIn: '5h',
      issuer: 'jonu',
      audience: 'jonu bhai'
    });
  res.send({ "token": token });
});

app.get('/', (req, res) => {
  res.send({ "status": "Up and Running..." });
});

app.listen(8080, () => {
  console.log('server running');
});