项目使用的是passport.js(http://passportjs.org/docs),所以对passport这个中间件研究了一番,在本项目中passport同express-session配合使用

其中配置express-sission:

app.use(session({
secret: secret,
store: store, //数据库存储session,
resave: false,
saveUninitialized: true,
cookie: cookie,
key: key
}));
对于数据库存储session:下面是代码(参考:https://www.npmjs.com/package/connect-mongo)
var mongoose = require('mongoose');
  mongoose.connect(connectionOptions);
 
 app.use(session({
    store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
其中的secret,key为字符串,cookie为一个object对象:配置如下:
cookie: {
path: "/",
expires: 15 * 60 * 1000 //失效时间
}
} passport.js的翻译: 安装:npm install passport

Authenticate

Authenticating requests is as simple as calling passport.authenticate() and specifying which strategy to employ. authenticate()'s function signature is standard Connect middleware, which makes it convenient to use as route middleware in Express applications.

将passport.authenticate()当做一个中间件来使用:
app.post('/login',
passport.authenticate('local'), function(req, res) { //local待续...
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user. //会将user信息(下面会讲怎么获取这个user信息)挂载在req.user上
res.redirect('/users/' + req.user.username);
}); By default, if authentication fails, Passport will respond with a 401 Unauthorized status, and any additional route handlers will not be invoked.
If authentication succeeds, the next handler will be invoked and thereq.user property will be set to the authenticated user.
当验证失败时,返回401,并且任何的route handles都不会调用.当验证成功后,req.user上将会挂载uer信息.

Note: Strategies must be configured prior to using them in a route. Continue reading the chapter onconfiguration for details.

使用之前先要配置一下.

Redirects

A redirect is commonly issued after authenticating a request.

app.post('/login', passport.authenticate('local', {

successRedirect: '/',                                  //这个是验证成功后的重定向

      failureRedirect: '/login'                             //这个是验证失败后的重定向

}));

In this case, the redirect options override the default behavior. Upon successful authentication, the user will be redirected to the home page.

If authentication fails, the user will be redirected back to the login page for another attempt.

Flash Messages (刷新)

Redirects are often combined with flash messages in order to display status information to the user.

重定向经常会配合着刷新,向客户端发送status 信息.

app.post('/login', passport.authenticate('local', {

successRedirect: '/',

       failureRedirect: '/login',

       failureFlash: true

}) );

Setting the failureFlash option to true instructs Passport to flash an error message using the message given by the strategy's verify callback, if any. This is often the best approach, because the verify callback can make the most accurate determination of why authentication failed.

这往往是最好的方法,因为验证回调可以精确测定验证失败的原因。

Alternatively, the flash message can be set specifically.

passport.authenticate('local', { failureFlash: 'Invalid username or password.' });

A successFlash option is available which flashes a success message when authentication succeeds.

passport.authenticate('local', { successFlash: 'Welcome!' });

Note: Using flash messages requires a req.flash() function. Express 2.x provided this functionality, however it was removed from Express 3.x. Use of connect-flash middleware is recommended to provide this functionality when using Express 3.x.

备注:用这个还需要使用req.flash()  所以一般不会设置.

Disable Sessions 禁用session

After successful authentication, Passport will establish a persistent login session. This is useful for the common scenario of users accessing a web application via a browser.

However, in some cases, session support is not necessary. For example, API servers typically require credentials to be supplied with each request. When this is the case,

session support can be safely disabled by setting the session option to false

app.get('/api/users/me',passport.authenticate('basic', { session: false }),function(req, res) {

    res.json({

       id: req.user.id,

      username: req.user.username

      });

});

对于常见的依靠session是有用的,但是对于api那种依赖credentials(证书).则是不可用的,这时候设置session为false.

app.get('/api/users/me', passport.authenticate('basic', { session: false }), function(req, res) {

    res.json({

         id: req.user.id,

        username: req.user.username

      });

});

Custom Callback

If the built-in options are not sufficient for handling an authentication request, a custom callback can be provided to allow the application to handle success or failure.

如果内置选项不足以处理的认证请求,可以提供一种定制的回调,以允许应用程序来处理成功或失败。

app.get('/login', function(req, res, next) {

passport.authenticate('local', function(err, user, info) {

    if (err) { return next(err); }

    if (!user) { return res.redirect('/login'); }

    req.logIn(user, function(err) {

        if (err) { return next(err); }

        return res.redirect('/users/' + user.username); });

})(req, res, next);

});

In this example, note that authenticate() is called from within the route handler, rather than being used as route middleware. This gives the callback access to the req and res objects through closure.

在本实施例,请注意,authenticate()被从路径处理程序中调用的,而不是被用作路由中间件。这使得通过关闭回调访问req and res objects 。

下面是讲解这个example:

If authentication failed, user will be set to false. If an exception occurred, err will be set. An optional infoargument will be passed, containing additional details provided by the strategy's verify callback.

The callback can use the arguments supplied to handle the authentication result as desired. Note that when using a custom callback, it becomes the application's responsibility to establish a session (by callingreq.login()) and send a response.

Configure

hree pieces need to be configured to use Passport for authentication:

  1. Authentication strategies     //认证策略
  2. Application middleware       //中间件
  3. Sessions (optional)             //session

Strategies

Passport uses what are termed strategies to authenticate requests. Strategies range from verifying a username and password, delegated authentication using OAuth or federated authentication using OpenID.

Passport使用所谓的strategies(策略)来验证请求。Strategies范围从验证用户名和密码,使用OAuth或使用OpenID联合身份验证委派验证。

Before asking Passport to authenticate a request, the strategy (or strategies) used by an application must be configured.

Strategies, and their configuration, are supplied via the use() function. For example, the following uses theLocalStrategy for username/password authentication.

通过use方法配置Strategy.LocalStrategy传入一个回调函数.function(username,passport,done) {}  获取的信息,通过done()传入到passport中,最后再进行序列化.

var passport = require('passport') ,

  LocalStrategy = require('passport-local').Strategy;         //Strategy

passport.use(new LocalStrategy(

   function(username, password, done) {              //这个被称为验证回调函数.

      User.findOne({ username: username }, function (err, user) {

        if (err) { return done(err); }

          if (!user) {

            return done(null, false, { message: 'Incorrect username.' });

          }

        if (!user.validPassword(password)) {

            return done(null, false, { message: 'Incorrect password.' });

         }

      return done(null, user); });

} ));

Verify Callback

This example introduces an important concept. Strategies require what is known as a verify callback. The purpose of a verify callback is to find the user that possesses a set of credentials.

本例介绍一个重要的概念。策略需要一个被称为验证回函数。一个验证回调函数的目的是要找到一个拥有一组凭据的用户。

When Passport authenticates a request, it parses the credentials contained in the request. It then invokes the verify callback with those credentials as arguments, in this case username and password. If the credentials are valid, the verify callback invokes done to supply Passport with the user that authenticated.

当Passport验证请求时,它解析请求中包含的数据。然后调用这些数据作为参数,在这种情况下,用户名和密码会作为回调的参数。如果数据有效,验证回调函数将调用done(null,user)。

return done(null, user);

If the credentials are not valid (for example, if the password is incorrect), done should be invoked with falseinstead of a user to indicate an authentication failure.

return done(null, false);

An additional info message can be supplied to indicate the reason for the failure. This is useful for displaying a flash message prompting the user to try again.

return done(null, false, { message: 'Incorrect password.' });

Finally, if an exception occurred while verifying the credentials (for example, if the database is not available),done should be invoked with an error, in conventional Node style.

return done(err);

Middleware

In a Connect or Express-based application, passport.initialize() middleware is required to initialize Passport. If your application uses persistent login sessions, passport.session() middleware must also be used.

app.configure(function() {

    app.use(express.static('public'));

    app.use(express.cookieParser());

    app.use(express.bodyParser());

    app.use(express.session({ secret: 'keyboard cat' }));

    app.use(passport.initialize());

    app.use(passport.session());

    app.use(app.router); });

Note that enabling session support is entirely optional, though it is recommended for most applications. If enabled, be sure to use express.session() before passport.session() to ensure that the login session is restored in the correct order.

express.session()要先于passport.session()配置

Sessions

In a typical web application, the credentials used to authenticate a user will only be transmitted during the login request. If authentication succeeds, a session will be established and maintained via a cookie set in the user's browser.

在一个典型的Web应用程序,用来验证用户的数据只会在登录请求期间发送的。如果验证成功,会话将被建立并通过在用户的浏览器中设置的cookie保持。

Each subsequent request will not contain credentials, but rather the unique cookie that identifies the session. In order to support login sessions, Passport will serialize and deserialize user instances to and from the session.

每个后续请求将不包含这些验证数据,而是唯一的Cookie标识会话。为了支持登录会话,passport会执行serializeUser(序列化)和deserializeUser(反序列化)的用户实例和会话。这个就是查数据库,来一次请求查一次.

passport.serializeUser(function(user, done) {

    done(null, user.id);

});

passport.deserializeUser(function(id, done) {

    User.findById(id, function(err, user) {

      done(err, user); });

});

In this example, only the user ID is serialized to the session, keeping the amount of data stored within the session small. When subsequent requests are received, this ID is used to find the user, which will be restored toreq.user.

在本实施例中,只有在user ID被序列化到session,保持存储在会话小内的数据量。当接收到的后续请求,这个ID被用来找到用户,这将挂载到req.user。

The serialization and deserialization logic is supplied by the application, allowing the application to choose an appropriate database and/or object mapper, without imposition by the authentication layer.

Username & Password

使用这个的目的是因为,使用本地策略

The most widely used way for websites to authenticate users is via a username and password. Support for this mechanism is provided by the passport-local module.

Configuration

var passport = require('passport') ,

   LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy( function(username, password, done) {

  User.findOne({ username: username }, function(err, user) {

    if (err) { return done(err); }

    if (!user) { return done(null, false, { message: 'Incorrect username.' }); }

    if (!user.validPassword(password)) { return done(null, false, { message: 'Incorrect password.' }); }

    return done(null, user); });

}

));

The verify callback for local authentication accepts username and password arguments, which are submitted to the application via a login form.

这个function就是扇面你提到的验证回调函数

Route

The login form is submitted to the server via the POST method. Using authenticate() with the localstrategy will handle the login request.

app.post('/login',
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login',
failureFlash: true })
);

Setting the failureFlash option to true instructs Passport to flash an error message using the messageoption set by the verify callback above. This is helpful when prompting the user to try again.

Parameters

By default, LocalStrategy expects to find credentials in parameters named username and password. If your site prefers to name these fields differently, options are available to change the defaults.

passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'passwd'
},
function(username, password, done) {
// ...
}
));

整理:

1.配置:

先配置session:

app.use(session({
  secret: secret,
  store: store, //数据库存储session,
  resave: false,
  saveUninitialized: true,
  cookie: cookie,
  key: key
}));

再配置中间件:

app.configure(function() {

    app.use(express.static('public'));

    app.use(express.cookieParser());

    app.use(express.bodyParser());

    app.use(express.session({ secret: 'keyboard cat' }));

    app.use(passport.initialize());

    app.use(passport.session());

    app.use(app.router); });

2.配置验证

app.post('/user/login',passport.authenticate('local',{

  failureRedirect: failureRedirect,
  failureFlash: failureFlash,

  badRequestMessage: badRequestMessage
}),handler)

)

其中handler是验证成功后的回调函数.

var handler =  function (req, res) {

return res.send('ok')
};

3.配置策略

passport.use('local', new LocalStrategy({

  usernameField: 'username',

  passwordField: 'password',

callback:passportCallback
  
}, passportCallback));   //这个指的是验证回调函数

passportCallback为:function (req, username, password, done) {}   (验证回调函数)

验证回调函数会将done的数据传入到序列化中.

4.序列化和反序列化

//序列化是将信息存储到session中

passport.serializeUser(function(user, done) {

    done(null, user.id);

});

//反序列化是将session中信息提取出来,挂在到req.user对象上

passport.deserializeUser(function(id, done) {

    User.findById(id, function(err, user) {

      done(err, user); });

});

补充:对于验证失败的时候,会调用req.flash()方法,因此要引进中间件 express-flash(或者connect-flash)

对于passport.js,每一次请求后都会更新数据库的失效时间,但客户端的exprise不会更新,这个要手动的更新才可以,设置如下:

resave: true,rolling: true
其中,rolling: true时会更新浏览器的cookie,

resave: true时会强制更新数据库的session

node的passport.js验证的更多相关文章

  1. [转]passport.js学习笔记

    概述 passport.js是Nodejs中的一个做登录验证的中间件,极其灵活和模块化,并且可与Express.Sails等Web框架无缝集成.Passport功能单一,即只能做登录验证,但非常强大, ...

  2. express+nodecoffee写passport登录验证实例(一)

    项目中要用到passport登录验证,环境如标题样:express框架,coffee模版引擎,node后台 一:建项目 直接用express命令建,虽然默认模版为jade,可以手动换成coffee哦. ...

  3. 网站注册与登录使用 bcrypt与 passport 双重验证 解释

    网站在登录前,需要进行注册收集用户基本信息,bcrypt 提供密码加密验证的方法,但是使用不正确,会给初学者带来各种问题. bcrypt 的安装: npm i bcrypt 经过测试,经常安装不成功, ...

  4. passport.js

    $(function(){ function isPlaceholder(){ var input = document.createElement('input'); return 'placeho ...

  5. quartz定时格式配置以及JS验证

    一个Cron-表达式是一个由六至七个字段组成由空格分隔的字符串,其中6个字段是必须的而一个是可选的,如下: ---------------------------------------------- ...

  6. JS验证图片格式和大小并预览

    用于上传图片的js验证: <%@ page language="java" contentType="text/html; charset=UTF-8"p ...

  7. 正则表达式的JS验证

    /判断输入内容是否为空    function IsNull(){        var str = document.getElementById('str').value.trim();      ...

  8. 【转】去除eclipse的JS验证

    第一步:去除eclipse的JS验证:将windows->preference->Java Script->Validator->Errors/Warnings->Ena ...

  9. js验证输入的金钱格式

    <html> <head> <title>js验证输入的金钱格式</title> <script type="text/javascri ...

随机推荐

  1. wordpress安装

    通过浏览器访问wordpress文件包 点击现在就开始,填写下面内容 我的填写 如出现下面情况,你得先创建一个数据库,再重试 数据库的创建 之后会出现 点击进行安装 安装成功 登录 主界面 写个文章, ...

  2. 在cmd下输入/g无效

    如图: 原来一:斜杠得是\ 二:命令和它之间没空格.这个符号和分号的使用是一样的.

  3. [转]Jquery通用开源框架之【ejq.js】

    ejq是一款非常小巧的JS工具库,未压缩才50K,在jquery的基础上对jquery缺失部分作了很好的弥补作用. 优点: 1.具有内置的模板解析引擎语法和angularjs相近减少学习成本 2.能够 ...

  4. PHP下利用PHPMailer配合QQ邮箱下的域名邮箱发送邮件(转)

    首先确定不是开启socks openssl phpinfo就可以知道 下载phpmailer   地址:https://github.com/PHPMailer/PHPMailer 下载完整, 个人和 ...

  5. Web 在线文件管理器学习笔记与总结(5)修改文件内容

    ① 读出要修改的文件的内容 ② 进行修改 ③ 将修改后的内容写进文件 index.php: <?php require 'dir.func.php'; require 'file.func.ph ...

  6. TextView实现圆角效果

    自定义一个Xml样式: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android ...

  7. php中json_decode()和json_encode()的使用方法

    php中json_decode()和json_encode()的使用方法 作者: 字体:[增加 减小] 类型:转载   json_decode对JSON格式的字符串进行编码而json_encode对变 ...

  8. Bootstrap页面布局19 - BS提示信息

    提示信息的设计 提示信息的类: .alert:提示信息类 .alert alert-danger: .alert alert-error: .alert alert-success: .alert a ...

  9. Java程序设计的基本原则

    Java程序设计的基本原则-1 1.面向对象 这是java编程里面大家公认的第一原则 2.优先使用对象组合而非类继承 3.分层 最典型的三层架构,表现层-->逻辑层-->数据层 表现层功能 ...

  10. Mschat控件示例升级错误处理方法

    将具有 3.5 版图表控件的 ASP.NET 3.5 网站升级到 ASP.NET 4 需要更改 web.config 和注册指令 将具有 3.5 版图表控件的 ASP.NET 3.5 网站升级到 AS ...