Passport isAuthenticated()始终返回TRUE

时间:2015-11-29 02:32:53

标签: node.js passport.js

使用护照本地身份验证,登录工作,我点击getStatus按钮,它可以工作,然后注销工作。但是在注销后,我在浏览器中单击“返回”,它仍然可以显示getStatus的完整内容。控制台登录isAuthenticated()仍然显示“您已登录”。这是简化的代码:

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);

1 个答案:

答案 0 :(得分:3)

查看护照索引时。使用app.use(passport.initialize())正在初始化每条路线上的空白用户。由于以上内容是在主app.js文件中使用而不是在特定路由中使用,因此每次向服务器发出请求时都会执行上述操作,即使有人未登录,也会创建一个空白用户。以下链接是护照的代码。

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

关于为什么护照配置不正确以达到预期效果并证明为什么我应该得到你想象中的互联网点的讨论。在谈论应用程序时,我必须确保我们在同一页面上。

对于讨论,我将使用以下文件结构引用应用程序:$ 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是否主持,它被称为Express Application。有些应用程序比其他应用程序更复杂,简单的应用程序可以是几个端点(A.K.A.URI和URL)。如果它是一个简单的应用程序,可以将API(应用程序接口)保存在主文件中,称为 app.js 。在更复杂的应用程序中,您将为您的文件组成名称,对于此示例,我将引用文件名 oAuth.js 来表示声明护照身份验证方法所代表的名称。

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

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

  

提供文件,例如图片,CSS,JavaScript和其他静态文件   在Express中内置中间件的帮助下完成 -   express.static。

     

传递目录的名称,该名称将被标记为位置   静态资产,以express.static中间件开始服务   文件直接。例如,如果你保留你的图像,CSS和   名为public的目录中的JavaScript文件,您可以这样做:

Express生成器将创建以下 app.js 文件,该文件配置非常重要。第一部分有一些非常有用的节点模块,这些节点模块没有表达的意思,最终你将导入一些自己的节点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 

路由就像迷你快递应用程序,记得我们第一次讨论某些应用程序如何变得比其他应用程序更复杂时?这就是您管理复杂性的方式,以便您的应用程序可以增长和蓬勃发展。假设您希望为您的爱心和精彩用户添加新功能。

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。它采用字符串的形式,并在此文件的顶部引用它的路径

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

此快速对象用法将允许您定义API,授权和非授权路由。您可以在此处声明对Express应用程序的经过身份验证的部分的引用。在app.use('/auth/',oAuth)之上声明的应用程序的任何部分都不会被验证。在URI和URL的/auth/部分下面声明的任何部分。将被认证。

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

快速生成器将在app文件中放置一些非常有用的额外内容。

// 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: {}
  });
});

由于您正在以不必要的复杂性污染应用程序命名空间,因此无意中会导致不受欢迎的身份验证影响。这更深入,因为它相对于格式化和配置应用程序接口以及如何在Node运行时环境中执行javascript文件,以及如何在构建复杂时使用和配置快速应用程序框架需要身份验证才能访问的应用程序。

现在回到你的问题,为什么你继续获得经过身份验证的用户,尽管没有人登录?这是因为您使用app.use('some string or some middleware')。要解决此问题,请删除所有身份验证处理并将其移至路由。在上面的示例中,它被引用为 oAuth.js 。定义需要在护照中间件后面进行身份验证的所有路由。

现在因为您的问题也与节点有关,并且您在评论中提到您是scrum的一部分,重要的是要声明所有这些信息都包含在express website中这是我最初链接我的答案的地方。尽管我告诉你,你需要一条路线并且护照配置不正确。所以任何煽动性评论"阅读手册"是因为我觉得你甚至没有调查我在最初答案中发送的链接,也没有阅读快递框架工作及其网站的任何其他部分。如果您计划了解任何node_modules和复杂框架的工作原理同样重要的是阅读它们并完成它们的教程,实际上在有一个入门和/或它们有API引用时会通过node_modules。通过在不尝试框架的任何部分的基础上进行应用程序开发,只会让您花费更多时间来编写糟糕的可破坏代码。如果您不了解node_modules的功能,它将显着减慢您的开发速度。了解其功能的最佳方式是阅读它们。这是我学习如何开发Web应用程序的咆哮/建议的全部内容。最终,您将能够在应用程序中重用许多教程代码。