簡體   English   中英

身份驗證發出帶有護照和Nginx作為代理服務器的Node.js

[英]Authentication issue Node.js with passport and Nginx as proxy server

我正在運行一個使用Passport.js在端口3000上進行身份驗證的Node應用程序.Nginx用作代理服務器偵聽端口80,代理將請求傳遞給端口3000.Passport.js用於驗證用戶。

身份驗證協議如下:用戶請求example.com,如果他未登錄,則會重定向到example.com/login。成功登錄后,用戶將再次重定向到example.com。

  • 當我嘗試使用Ipad上的Safari 6和Internet Explorer 9(懷疑客戶有同樣的問題)登錄時,會出現此問題。 當使用正確的憑據時,應用程序會重定向到example.com/login而不是example.com/。

  • 例如,Chrome 40中不會出現此問題。

  • 在Safari中使用example.com:3000避免使用nginx時不會出現此問題。
  • 更糟糕的是:有時候它沒有明顯的原因。

我懷疑它與Nginx以及請求文件的順序有關。

Nginx配置:

server {
    listen 80;
    location / {
            proxy_pass http://127.0.0.1:3000;
    }
}

部分應用代碼:

app.post('/api/login', function (req, res, next) {
passport.authenticate('local-login', function (err, user, info) {
  if (err) {
    return next(err);
  }
  if (!user) {
    return res.status(401).send(info);
  }
  req.logIn(user, function (err) {
    if (err) {
      return next(err);
    }
    return res.send({
      username: user.username
    });
  });
})(req, res, next);
});

app.get('/', isLoggedIn, function (req, res) {
  res.sendFile(__dirname + '/client/views/index.html');
});


function isLoggedIn(req, res, next) {
  if (!req.isAuthenticated()) {
    res.redirect('/login');
  } else {
    next();
  }
}

我想知道是否有人可以幫助我。 我很樂意在需要時提供額外的代碼或解釋。

Nginx原來與之無關。 通過使用example.com:3000直接訪問,偶爾也會出現問題。

我注意到瀏覽器曾說過我訪問過example.com並且正在顯示example.com/login。 我在互聯網上找不到任何證據,但我懷疑Safari / IE9緩存重定向的頁面並將其鏈接到原始URL。 所以這是接下來發生的事情的故事情節。

  1. 用戶瀏覽example.com/
  2. 重定向到example.com/login(瀏覽器緩存example.com/但保存登錄頁面)
  3. 用戶登錄並重定向到example.com/
  4. 瀏覽器具有/在緩存中並加載登錄頁面。
  5. 無法解釋的錯誤和開發人員的頭痛。

通過添加中間件來“解決”,在請求時不添加緩存頭。

app.get('/', isLoggedIn, noCache, function (req, res) {
  res.sendFile(__dirname + '/client/views/index.html');
});

function noCache(req, res, next) {
  res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
  res.header('Expires', '-1');
  res.header('Pragma', 'no-cache');
  next();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM