2016-06-13 65 views
4

我有一個使用Express 4和Passport 0.3.2的應用程序。我已經設置了一個passport-local策略,當/session端點發送用戶名和密碼時,該策略會獲取正確的用戶信息。PassportJS和Express 4沒有正確保存Cookie /會話

但是,用戶信息永遠無法正確保存。因此,req.user在所有收聽者中始終未定義,並且req.isAuthenticated()始終返回false。

我看過其他文章,經常會發現中間件安裝的順序問題,但是我已經以正確的方式對它們進行了排序,所以我不知道該從哪裏下載。

這裏是我的/sessionPOST聽衆:

app.post("/session", 
    passport.authenticate('local'), 
    (req: any, res: any) => { 
     // if we reach this point, we authenticated correctly 
     res.sendStatus(201); 
    } 
); 

這裏是我的LocalStrategy設置:

passport.use(new LocalStrategy(
    (username, password, done) => { 
     let users = userRepository.getAll(); 

     let usernameFilter = users.filter(u => u.getUsername() === username); 
     if (!usernameFilter || usernameFilter.length !== 1) { 
      return done(null, false, { message: 'Incorrect username.' }); 
     } 

     if (!password || password !== "correct") { 
      return done(null, false, { message: 'Incorrect password.' }); 
     } 

     return done(null, usernameFilter[0]); 
    } 
)); 

這裏是我的應用程序設置:

let app = express(); 
app.use(cookieParser()); 
app.use(bodyParser.json()); 
app.use(expressSession({ 
    secret: 'my secret key', 
    resave: true, 
    saveUninitialized: true 
})); 
app.use(passport.initialize()); 
app.use(passport.session()); 

我使用以下依賴版本:

"body-parser": "^1.15.1", 
"cookie-parser": "^1.4.3", 
"express": "^4.13.4", 
"express-session": "^1.13.0", 
"passport": "^0.3.2", 
"passport-local": "^1.0.0" 

我添加了一個回調到我的POST /session,但拋出一個錯誤。這是我的回調:

app.post("/session", 
    passport.authenticate('local', { 
     session: false 
    }), 
    (req: express.Request, res: express.Response) => { 
     req.logIn(req.user, (err: any) => { 
      if (err) 
       throw err; 
     }); 

     // if we reach this point, we authenticated correctly 
     res.sendStatus(201); 
    } 
); 

我收到以下錯誤拋出:

Error: Failed to serialize user into session

+0

我相信你需要在你的POST – pulse0ne

回答

2

從護照文檔:

Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response.


啊,好,我們正在取得進展。您必須配置護照才能序列化和反序列化用戶信息。有關信息,請參閱this。應該指出,您將用您自己的數據庫訪問對象替換User

+0

中調用護照的'.login()'函數謝謝@ pulse0ne,我已經添加了這個,現在我收到一個錯誤。我已經更新了我的主要問題。 –

+0

@JamesMonger這實際上是一個好兆頭,你更接近於正確地工作。我已經更新了我的答案 – pulse0ne

-1

我在遇到相關問題時從Google搜索中找到此問題。

我意識到express-session不會持續會話,例如服務器重新啓動之間。 Read here for more info

所以我換express-sessioncookie-session代替:

app.use(cookieSession({ 
    name: 'MyAppName', 
    keys: ['very secret key'], 
    maxAge: 30 * 24 * 60 * 60 * 1000 // 30 days 
})); 

然後PassportJS是堅持我的會議,沒有進一步的變化需要!