Passport isAuthenticated()总是返回TRUE

使用护照本地authentication,login工程,我点击getStatusbutton,它的工作原理,然后注销工程。 但注销后,我在浏览器中点击BACK,仍然可以显示getStatus的全部内容。 控制台loginisAuthenticated()仍然说“你已经login”。 这是简化的代码:

 var express = require('express'); var passport = require('passport'); var net = require('net'); var bodyParser = require('body-parser'); var http = require('http'); var multer = require('multer'); var cp = require('child_process'); var exec = require('child_process').exec; var sys = require('sys'); var path = require('path'); var util = require('util'); var session = require('express-session'); var crypto = require('crypto'); var sqlite3 = require('sqlite3'); ///////////////////////////////////////////////// var LocalStrategy = require('passport-local').Strategy; var db = new sqlite3.Database('./myPassword.db'); passport.use(new LocalStrategy(function(username, password, done) { console.log("step 2: Client sent you user: " + username + " password: " + password); db.get('SELECT slat FROM users WHERE username = ?', username, function(err, row) { if (!row) return done(null, false); console.log("step 4"); db.get('SELECT username, id FROM users WHERE username = ? AND password = ?', username, password, function(err, row) { console.log("step 6"); if (!row) return done(null, false); console.log("step 8"); return done(null, row); }); }); })); passport.serializeUser(function(user, done) { return done(null, user.id); }); passport.deserializeUser(function(id, done) { db.get('SELECT id, username FROM users WHERE id = ?', id, function(err, row) { if (!row) return done(null, false); return done(null, row); }); }); ///////////////////////////////////////////////// var isAuthenticated = function(req, res, next) { //if (req.user.authenticated) if (req.isAuthenticated()) { console.log("Very good, you are logged in ..."); return next(); } console.log("Sorry, you are NOT logged in yet ..."); res.send(200); }; ///////////////////////////////////////////////// var app = express(); ///////////////////////////////////////////////// var server = http.createServer(app); ///////////////////////////////////////////////// app.use(function(req, res, next) { if (!req.user) { console.log('Cannot display 1 ...'); res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate'); } console.log('Cannot display 2 ...'); next(); }); app.use(express.static('../client/', {index: 'login.html'} )); app.use(bodyParser()); app.use(session({ secret: 'my test cookie' })); app.use(passport.initialize()); app.use(passport.session()); app.post('/auth/login', passport.authenticate('local', { successRedirect: '/index.html#/uploads', failureRedirect: '/login.html', })); app.get('/auth/logout', function(req, res) { console.log("logging out ......"); req.session = null; req.logout(); res.send(200); }); app.get('/', isAuthenticated, function(req, res) { res.sendfile(path.resolve('../client/index.html')); }); app.get('/systemStatus', isAuthenticated, function(req, res) { console.log("asking for Json data from backend"); // skip details here ... }); server.listen(5678); 

当看护照指数。 使用app.use(passport.initialize())正在初始化每个路由上的空白用户。 由于以上是在主app.js文件中使用的,而不是在特定的路由中使用,所以每次向服务器发出请求时都会执行该操作,即使有人没有login,本质上也会创build一个空白用户。下面的链接是护照的代码。

https://github.com/jaredhanson/passport/blob/master/lib/authenticator.js

对于这个为什么护照configuration不正确的理想为什么我值得你想象的互联网点的讨论。 谈论应用程序时,我将不得不确保我们在同一页面上。

对于讨论,我将使用下面的文件结构引用应用程序: $ npm install -g express-generator

(实际上有更多的文件,但你可以在快递网站上查看)。

 myProject |___bin |___www.js //server.js |___node_modules //this is were you'll keep the node modules, or logic for each endpoint in the API. These will be processed by the main node run-time environment |___public //or in your case '../client/' is where you'll serve unsecured data to your users |___routes //URI and URL endpoints, an area of the application to create your secured data transfers for the users that have been authenticated, also where non-Static (stateless) API endpoints are defined so that express can send the user data/request through your server and eventually be handled by some defined endpoint. |___index.js |___views //if using a view engine |___app.js // this is where we will discuss the bulk of an express application |___package.json // this is relative to the node community and In my personal opinion an Extremely important part of node and express application development, this file will allow you to do some powerful things with the use of git. 

app.js是你的APP主持人,它被称为快速应用程序。 一些应用程序比其他应用程序更复杂,一个简单的应用程序可以是几个端点(AKA URI和URL)。 如果这是一个简单的应用程序,可以将API(应用程序接口)保存在主文件app.js中 。 在一个更复杂的应用程序中,您将为您的文件组成名称,对于此示例,我将引用文件名称oAuth.js来表示声明通行证身份validation方法。

根据我使用Web应用程序的经验,你将有一个登陆页面,一个主页面,一个login页面或者某种新闻(通常在静态文件夹中定义为index.html )。在你的情况下,将静态文件夹定义为'。 ./client/“并传递对象index.html。

在Express 4.X的最新版本中,服务静态文件按照以下规定的方式完成。

在Express – express.static中借助内置的中间件来完成对图片,CSS,JavaScript等静态文件的提供。

将待标记为静态资产位置的目录名称传递给express.static中间件,直接开始提供文件。 例如,如果您将图像,CSS和JavaScript文件保存在名为public的目录中,则可以这样做:

Express生成器将创build下面的app.js文件,这是configuration一个非常重要的方法。 第一部分有一些非常有用的节点模块,这些节点模块没有被定义为明确的,并且最终将导入一些自己的节点API

 var express = require('express'), path = require('path'), //core node module logger = require('morgan'), //allows you to see the console.logs during development and see incoming and outgoing messages to the server. It also displays `console.log()` defined in any node_module, express route, and express app file. cookieParser = require('cookie-parser'), //helps when trying to handle cookies bodyParser = require('body-parser'); //helps when parsing certain types of data 

路线就像迷你快车应用程序,记得当我们第一次讨论一些应用程序如何变得比其他应用程序更复杂? 这就是你如何pipe理复杂性,所以你的应用程序可以发展壮大。 假设你想为你的爱和美好的用户添加新的function。

 var route = require('.routes/index',// this is importing the the logic of the URI and URL enpoint to this file. It will be referenced as the second argument in the route and configuration references below. oAuth = require('.routes/oauth') // this is the file where you'll place all of the passport logic you have previously wrote. Any other authenticated routes need to be defined in this file. // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); //alot of people are also using EJS equally if not more 

现在安装Express-Generator提供的基本中间件

 app.use(logger('dev')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(bodyParser.json({ type: 'application/vnd.api+json' })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); //this style declaration ensures you hit what ever directory you want to by changing public as long as that directory exists. 

路由URI和URL端点由您定义为 – > express。 它采用string的forms,并在这个文件的顶部引用它的路由

 app.use('/', routes); //unsecured landing page 

这个明确的对象使用将允许您定义API,授权和未授权的路线。 这是您将声明您对快速应用程序的已validation部分的引用。 在app.use('/auth/',oAuth)上面声明的应用程序的任何部分都不会被authentication。 在URI和URL的/auth/部分下面声明的任何部分。 将被authentication。

 app.use('/auth/', oAuth); 

一些额外的快递生成器将放在应用程序文件中是非常有用的。

 // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); 

由于您正在以不必要的复杂性污染您的应用程序名称空间,因此无意中造成了您不希望的身份validation影响。 这更深入,因为它涉及格式化和configuration您的应用程序接口,以及如何在Node运行时环境中执行JavaScript文件,以及在构build需要身份validation的复杂应用程序时如何使用和configuration快速应用程序框架访问。

现在回到你的问题,为什么你不断得到一个authentication的用户,虽然没有人login? 这是因为你使用app.use('some string or some middleware') 。 要解决这个问题,请删除所有的validation处理并将其移至路由。 在上面的例子中,它被引用为oAuth.js 。 在护照中间件后面定义任何需要身份validation的路由。

现在,因为你的问题也是关于节点,你在评论中提到你是一个Scrum的一部分,所以说明所有这些信息都包含在快速网站上 ,这是我最初链接我的答案的地方。 尽pipe我告诉你,你需要一个路线,护照configuration不正确。 所以,所有的煽动性的评论“阅读手册”都是因为我觉得你甚至没有调查我在我的初步答复中发送的链接,也没有阅读任何其他部分的快速框架和他们的网站。 如果您打算了解任何node_modules和复杂框架的工作方式,阅读这些内容并执行其教程同样重要,那么在开始使用和/或具有API参考时,实际上需要通过node_modules。 通过爆发到应用程序开发,而不尝试框架的任何部分的基础知识,只会让你花更多的时间来编码坏易破的代码。 如果您不了解node_modules函数的方式,会显着减慢您的开发速度。 了解其function的最好方法是阅读它们。 这就是为了学习如何开发Web应用程序而提出的build议。 最终,您将能够在应用程序中重复使用很多教程代码。