本文轉載自:衆成翻譯
譯者:網絡埋伏紀事
連接:http://www.zcfy.cc/article/1755
原文:https://blog.risingstack.com/node-hero-node-js-authentication-passport-js/node
本教程中將學習如何使用 Passport.js 和 Redis 實現一個本地 Node.js 身份驗證策略。git
在一頭扎進實際代碼以前,咱們先看看本章中要用到的新技術。github
簡單、 不花哨的 Node.js 身份驗證 - passportjs.orgredis
Passport 是一個 Node.js 身份認證中間件,咱們將把它用於會話管理。數據庫
Redis 是一個開源的(BSD 許可)、內存中的數據結構倉庫,被用做數據庫、緩存和消息代理中間件 - redis.io。express
咱們打算把用戶的會話信息存到 Redis 中,而不是在會話過程的內存中。經過這種方式,咱們的應用程序會更容易擴展一些。json
出於演示目的,下面咱們建立一個只作以下事情的應用程序:緩存
顯示一個登陸表單,服務器
顯示兩個受保護頁面:cookie
概述(profile)頁面,
secured notes
在前一章你已經學習了如何組織 Node.js 項目的結構,因此下面咱們就開始用所學的知識!
咱們打算採用以下結構:
├── app | ├── authentication | ├── note | ├── user | ├── index.js | └── layout.hbs ├── config | └── index.js ├── index.js └── package.json
正如你所見,咱們會圍繞着功能來組織文件和目錄。咱們將有一個用戶頁,一個備註頁,和一些與身份驗證相關的功能。
完整的代碼下載在 https://github.com/RisingStack/nodehero-authentication。*
咱們的目標是實現以下的身份驗證流程到咱們的應用程序中:
用戶輸入姓名和密碼
應用程序檢查是否匹配
若是匹配,就發送一個 Set-Cookie
響應頭,用它來驗證以後的頁面
當用戶從同一域訪問頁面時,以前設置的 cookie 會被添加到全部的請求中
用這個 cookie 驗證受限制的頁面
爲設置像這樣的身份驗證策略,請遵循以下三個步驟:
咱們打算用 Express 做爲服務器框架 - 能夠經過閱讀咱們的 Express 教程,來學習更多關於此主題的知識。
// file:app/index.js const express = require('express') const passport = require('passport') const session = require('express-session') const RedisStore = require('connect-redis')(session) const app = express() app.use(session({ store: new RedisStore({ url: config.redisStore.url }), secret: config.redisStore.secret, resave: false, saveUninitialized: false })) app.use(passport.initialize()) app.use(passport.session())
在這裏咱們作了什麼?
首先,咱們 require 了全部會話管理所需的依賴。以後,咱們從 express-session
模塊建立了一個新的實例,用它來存儲會話。
爲後備存儲,咱們用了 Redis。可是,你可使用任何其它數據庫,好比 MySQL 或者 MongoDB。
Passport 是使用插件的一個很好的示例庫。對於本教程,咱們添加 passport-local
模塊,該模塊讓咱們能夠很容易集成使用用戶名和密碼的簡單本地身份驗證策略。
爲簡單起見,在本例中,咱們沒有使用第二個後備存儲,只用了一個內存中的 user 實例。在真實應用程序中,findUser
會在數據庫中查找一個用戶。
// file:app/authenticate/init.js const passport = require('passport') const LocalStrategy = require('passport-local').Strategy const user = { username: 'test-user', password: 'test-password', id: 1 } passport.use(new LocalStrategy( function(username, password, done) { findUser(username, function (err, user) { if (err) { return done(err) } if (!user) { return done(null, false) } if (password !== user.password ) { return done(null, false) } return done(null, user) }) } ))
一旦 findUser
返回 user 對象,剩下的惟一的事情是比較提供的用戶以及真實密碼,看看是否匹配。
若是匹配,就讓用戶進入(經過將用戶返回給 passport - return done(null, user)
);若是不匹配,就返回一個未受權錯誤(經過什麼都不返回給 passport - return done(null)
)。
要添加受保護的端點,就得利用 Express 所用的中間件模式。爲此,先建立身份驗證中間件:
// file:app/authentication/middleware.js function authenticationMiddleware () { return function (req, res, next) { if (req.isAuthenticated()) { return next() } res.redirect('/') } }
這段代碼有一個做用,就是若是用戶被驗證(有正確的 cookies),就調用下一個中間件;不然就重定向到用戶登陸頁面。
用這種方式與把新中間件添加到路由定義同樣簡單。
// file:app/user/init.js const passport = require('passport') app.get('/profile', passport.authenticationMiddleware(), renderProfile)
在本教程中,你已經學習瞭如何給應用程序添加基礎的身份驗證。以後,就能夠用不一樣的身份驗證策略擴展它,好比 Facebook 或 Twitter。在 http://passportjs.org/ 上能夠找到更多策略。
完整的示例代碼放在 GitHub 上,你能夠看看這裏:https://github.com/RisingStack/nodehero-authentication。
下一章主要涉及 Node.js 應用程序的單元測試。你會學習單元測試、測試金字塔、測試替代等概念。