为什么passport.js工作不正常?虽然我传递了正确的令牌,但我还是未经授权

时间:2017-09-07 08:57:16

标签: express jwt passport.js

这是对的吗? 我不明白为什么我每次都会被擅自。 我认为这个use()函数没有被调用? // Passport.js

const JwtStrategy = require('passport-jwt').Strategy;
    const ExtractJwt= require('passport-jwt').ExtractJwt;
    const User = require('../models/user');
    const config = require('../config/database');
    module.exports= function(passport){
        let opts= {};
        opts.jwtFromRequest=ExtractJwt.fromAuthHeaderAsBearerToken();
        opts.secretOrKey = config.secret;
        passport.use(new JwtStrategy(opts, (jwt_payload,done)=>{
            console.log('test');  // its not printing
            User.getUserById(jwt_payload._doc._id,(err,user)=>{
                  if(err){
                      return done(err,false);
                  }
                  if(user){
                        return(null,user);
                  }
                  else{
                      return (null,false);
                  }
              });
        }));
    }

这是我的app.js文件。在我的视图中这是正确运行。

//1. Import required files
//-----------------------------------
const express = require('express'); // Core files and functions API
const path = require('path'); // Path setting API(Part of core API)
const bodyParser= require('body-parser'); //Text to JSON paser API
const cors= require('cors'); // //Cross-Origin Resource Sharing (CORS) API
const mongoose=require('mongoose');  // MongoDb API
const passport= require('passport'); //Authentication Framework API
 //-----------------------------------

 //2.Database Connection
//-----------------------------------
const config = require('./config/database'); //File containing connection string
mongoose.connect(config.database,{useMongoClient:true});// function to connect
//Connection confirmation
mongoose.connection.on('connected',()=>{  
    console.log('connected successfully to'+config.database);
});
mongoose.connection.on('error',(err)=>{
    console.log('Database error'+err);
});
//-----------------------------------

//4.Middlewares: CORS and Body-parser implementation.
//-----------------------------------
const app = express();
app.use(cors()); //Cross-Origin Resource Sharing (CORS)
app.options(cors({origin:'*'}));  //Use your origins.
app.use(cors({origin:'*'}));      //Use your origins.
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());//Text to json convertor 
//-----------------------------------

//5.passport middleware implementation for authentication
//-----------------------------------
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
//-----------------------------------

//6.Routers
//-----------------------------------
/*Any*/
const users= require('./routes/users');
app.use('/users',users);

//-----------------------------------


//7.Port declaration for server
//-----------------------------------
const port = 3000;
//-----------------------------------

//8.Set static folder(front end/Angular-2)
//-----------------------------------
app.use(express.static(path.join(__dirname,'public')));
//-----------------------------------




//9.Fire-up server
//-----------------------------------
app.listen(port,()=>{
console.log('server started on port:'+port);
});
//-----------------------------------

这是路由器文件。我认为这个文件工作正常。如果我没有使用身份验证,那么路由工作正常。

const express = require('express');
const router= express.Router();
const passport=require('passport');
const jwt= require('jsonwebtoken');
const User=require('../models/user');
const config = require('../config/database');

//Register Router
router.post('/register',(req,res,next)=>{
    let newUser = new User({
        name:req.body.name,
        email:req.body.email,
        username:req.body.username,
        password:req.body.password
    });
    console.log(newUser);
    User.addUser(newUser,(err,user)=>{
        console.log(newUser);  
        if(err){
              res.json({success:false,msg:'fails to register user'});
          }
          else{
            res.json({success:true,msg:'User registered successfully'});
          }

    });
});

//Authentication Router
router.post('/authenticate',(req,res,next)=>{
    const username =req.body.username;
    const password= req.body.password;
    console.log("reached auth endpoint");
    console.log(req.body);
    User.getUserByUsername(username,(err,user)=>{
        if(err) throw err;
        if(!user){
           return res.json("User Not Found!!");
        }
        User.comaparePassword(password,user.password,(err,isMatch)=>{
            if(err) throw err;
            if(isMatch){
                const token = jwt.sign(user,config.secret,{
                    expiresIn:604800
                });

                res.json({
                   success:true,
                   token:'JWT'+token,
                   user:{
                     id:user._id,
                     name: user.name,
                     username:user.username,
                     email:user.email
                  }
                });
            }else{
                return res.json('Wrong password!!');
            }

        });
    });
});

//Profile Router
router.get('/profile',passport.authenticate('jwt',{session:false}),(req,res,next)=>{
    res.send("Profile Page");
});

//Validate Router
router.get('/validate',(req,res,next)=>{
    res.send("Validation Page");
});

module.exports=router;

1 个答案:

答案 0 :(得分:0)

我的解决方案是 - 使用passport-jwt 2.0.0 它的工作非常好