2016-11-13 51 views
1

我有一個絕對的噩夢試圖用我的快速應用程序設置智威湯遜!認爲我現在主要工作,我有一個註冊路線和登錄路線,這兩個工作正常,並生成有效令牌,我有我的'/用戶'路線中的另一條路線,我測試身份驗證,這一切都很好。但是我有另一個包含'/ api'路徑的文件,這是認證實際上非常重要的地方,我有一條類似的嘗試訪問req.user的測試路線(就像我在其他路線中那樣),但它看起來像req。用戶未定義。經過一些調試它看起來像用戶在req.account這是非常奇怪的,我不明白爲什麼它不是在req.user護照JWT req.user在我的其中一條路線中未定義

我定義我在/config/passport.js JWT戰略

'use strict'; 
const User = require('../models/user'), 
     config = require('./main'), 
     JwtStrategy = require('passport-jwt').Strategy, 
     ExtractJwt = require('passport-jwt').ExtractJwt; 

//exported to be used by passport in server set up 
module.exports = function (passport) { 
    const jwtOptions = { 
    // Telling Passport to check authorization headers for JWT 
    jwtFromRequest: ExtractJwt.fromAuthHeader(), 
    // Telling Passport where to find the secret 
    secretOrKey: config.secret 
    }; 

    const jwtLogin = new JwtStrategy(jwtOptions, function(payload, done) { 
    User.findById(payload._id, function(err, user) { 
     if (err) { return done(err, false); } 

     if (user) { 
     done(null, user); 
     } else { 
     done(null, false); 
     } 
    }); 
    }); 

    passport.use(jwtLogin); 

} 

護照被作爲參數傳遞給此,然後在主快遞文件中初始化

這裏是/ users路徑文件,這工作正常。發送GET請求/用戶/ isAuth與Authorization頭和「智威湯遜」工作正常,我讓我的用戶名發回給我

"use strict"; 
const express = require('express'), 
     router = express.Router(), 
     jwt = require('jsonwebtoken'), 
     User = require('../models/user'), 
     config = require('../config/main'), 
     passport = require ('passport'); 

function generateToken(user) { 
    return jwt.sign({_id: user._id}, config.secret, { 
     expiresIn: 10080 
    }); 
} 
. 
. Here are routes for login and register they perform as expected 
. and work fine 
. 
/* ================================== 
     Test Authentication Route 
    ================================== */ 
router.get('/isAuth', passport.authenticate('jwt', { session: false }), function(req, res) { 
    console.log(req.user); 
    res.json({username: req.user.username}); 
}); 



module.exports = router; 

在這個文件中,雖然,對於API的路線發送到GET/API的請求/ testAuth與以前完全一樣,具有相同的標記和相同的標頭,我返回no req.user並在控制檯中看到req.user未定義。但在控制檯中,似乎只有req.account這樣的用戶對象?我不明白這裏發生了什麼,希望有人能幫助!

"use strict"; 
const express = require('express'), 
     router = express.Router(), 
     jwt = require('jsonwebtoken'), 
     Server = require('../models/server'), 
     passport = require('passport'); 

// Test route to see if logged in user is matt 
router.get('/testAuth', passport.authorize('jwt', { session: false }), function(req, res) { 
    console.log(req.user); 
    if (req.user) { 
     if(req.user.username == "matt") { 
     res.send("You are matt!"); 
     } else { 
     res.send("You are not matt!"); 
     } 
    } else { 
     res.send("no req.user"); 
    } 

}) 

module.exports = router; 

回答

2

您正在使用您的testAuth路線passport.authorize,這是對於已經登錄並具有會話信息的用戶。既然你不使用會話存儲你沒有持久req.user對象,所以應該對所有路由都使用passport.authenticate

http://passportjs.org/docs/authorize