)
freeCodeCamp Advanced Node and Express用 Passport LocalStrategy 实现本地认证策略Authentication Strategies【免费下载链接】freeCodeCampfreeCodeCamp.orgs open-source codebase and curriculum. Learn math, programming, and computer science for free.项目地址: https://gitcode.com/GitHub_Trending/fr/freeCodeCamp本篇围绕 freeCodeCamp 课程中 Advanced Node and Express 项目的一个核心关卡 Authentication Strategies 展开讲解如何用 Passport 的passport-local策略实现用户名 密码的本地认证包括LocalStrategy的注册方式、done回调的三种返回语义、为什么策略代码必须放在数据库连接回调内以及自动化测试是如何校验你的实现的。读完后你能把这套认证策略完整跑通并理解它在整个登录链路/login路由 → 中间件 → 会话中的位置。在课程项目中的位置该关卡属于 freeCodeCamp 课程仓库中质量保证与测试Quality Assurance超级块下的 Advanced Node and Express 项目块关卡定义见 关卡文档块内关卡顺序见 advanced-node-and-express.json。在关卡顺序中它排在完成模板引擎Pug、配置 Passport 与 express-session、实现用户序列化serializeUser/deserializeUser和数据库连接之后。也就是说到达本关卡时你的项目已经具备pug视图引擎app.set(view engine, pug)、views指向./views/pugexpress-session会话secret取自process.env.SESSION_SECRETresave: true、saveUninitialized: true、cookie: { secure: false }以及app.use(passport.initialize())和app.use(passport.session())passport.serializeUser/passport.deserializeUser并且序列化/反序列化代码以及路由都包裹在myDB(async client { ... })的数据库连接回调中见 Set up Passport 与 Implement the Serialization of a Passport User。本关卡的任务是补上认证策略这块拼图告诉 Passport如何验证一个用户而不是在哪个路由上调用验证后者是下一关 How to Use Passport Strategies 的内容。什么是策略Strategy按原文档的定义策略是一种认证用户的方式。你可以基于本地保存的信息前提是先让用户注册过来认证也可以依赖 Google、GitHub 等第三方提供商。本项目使用 Passport 中间件——Passport 提供了一整套策略支持用户名/密码、GitHub、Google 等多种认证方式。本关卡用到的策略是passport-local~1.0.0课程模板已预先作为依赖写入package.json你只需要在自己的服务器代码中引入它const LocalStrategy require(passport-local);注册 LocalStrategy完整代码与逐行解析原文档要求用passport.use注册一个实例化后的LocalStrategy对象并且特别强调从这一步起的代码都要封装在数据库连接回调内因为策略依赖数据库。完整写法如下passport.use(new LocalStrategy((username, password, done) { myDataBase.findOne({ username: username }, (err, user) { console.log(User ${username} attempted to log in.); if (err) return done(err); if (!user) return done(null, false); if (password ! user.password) return done(null, false); return done(null, user); }); }));这段代码定义了本地认证的完整流程先用用户输入的username去数据库查用户再比对密码只要没有命中错误分支就把user对象交还给 Passport用户即被认证通过。逐行看done回调的三种调用语义这是理解 Passport 本地策略的关键调用含义本例对应场景done(err)认证过程本身出错例如数据库查询失败findOne返回errdone(null, false)凭证无效用户不存在或密码不匹配!user或password ! user.passworddone(null, user)认证成功把完整用户对象交给 Passport用户名、密码都匹配注意密码比对采用的是明文全等比较password ! user.password。这并不是疏漏——课程在后面的 Hashing Your Passwords 关卡关卡文档会明确要求引入bcrypt~5.0.0把这一行替换为if (!bcrypt.compareSync(password, user.password)) { return done(null, false); }并在注册路由用bcrypt.hashSync(req.body.password, 12)生成哈希后再入库。也就是说本关卡先建立策略骨架后续关卡再加固密码存储这一安全环节。为什么必须放在数据库连接回调里原文档用加粗文字强调make sure this (as well as everything from this point on) is encapsulated in the database connection。原因在于策略的LocalStrategy回调中调用了myDataBase.findOne而myDataBase这个集合句柄是在myDB(async client { ... })回调内通过client.db(database).collection(users)创建的。从源码结构看把passport.use(...)放在回调之外myDataBase要么未定义、要么指向已关闭的旧连接。因此正确结构是myDB(async client { const myDataBase await client.db(database).collection(users); // 序列化、反序列化也在这里 passport.serializeUser((user, done) { done(null, user._id); }); passport.deserializeUser((id, done) { myDataBase.findOne({ _id: new ObjectID(id) }, (err, doc) { done(null, doc); }); }); // 本关卡注册 LocalStrategy passport.use(new LocalStrategy((username, password, done) { myDataBase.findOne({ username: username }, (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); }); })); // 后续路由/login 等也在这里 }).catch(e { // 连接失败时渲染错误页 }); // app.listen 放在 myDB 回调之外其他策略以 GitHub 策略为例原文档还指出很多策略都通过各自不同的配置项搭建通常参照该策略仓库的 README 即可轻松配置。它举了 GitHub 策略的例子——你不需要关心用户名或密码因为用户会被跳转到 GitHub 的认证页只要用户在 GitHub 处于登录状态并同意授权GitHub 就会把用户资料返回给你使用。块内后续的三个 Implementation of Social Authentication 关卡见 关卡顺序正是把这一思路落地。自动化测试如何校验你的实现本关卡是challengeType: 2项目型关卡测试代码内置在关卡文档的--hints--区块中原文档 的 L41-L77。它通过/_api/package.json和/_api/server.js两个内部端点拉取你的代码做静态断言依赖检查package.json的dependencies中必须列出passport-local引入检查server.js中必须匹配/require.*(|)passport-local(|)/即确实require(passport-local)策略注册检查必须出现new LocalStrategyassert.match(data, /new LocalStrategy/)证明你告诉 Passport 使用了一个新策略数据库查询检查必须出现findOneassert.match(data, /findOne/)证明本地策略是基于输入的用户名执行findOne查询的而不是硬编码用户。对照原文档的验收标准passport-local是依赖、策略已实例化并注册、策略内使用findOne查询用户名——三条全部满足后本关卡才算完成。与下一关的衔接策略注册与策略调用是分开的两步本关卡末尾原文档预告在下一步你将设置如何真正调用认证策略来基于表单数据验证用户。 在下一关 How to Use Passport Strategies 中index.pug里的登录表单默认被if showLogin隐藏需要在res.render时传入showLogin: true才会显示表单POST到/login该路由需要挂载中间件passport.authenticate(local, { failureRedirect: / })认证通过后才执行重定向到/profile的响应认证成功时完整用户对象保存在req.user上这正是前面序列化/反序列化配合会话 cookie 的工作成果。在尚未实现注册流程之前对/login的 POST 请求会失败并重定向回首页/服务端控制台会打印User {USERNAME} attempted to log in.——这是验证本关策略代码已生效的最直接信号策略回调执行了只是查不到已注册用户。小结与参考本关卡在整条认证链路中的职责可以概括为策略本关定义怎样判定一个用户通过——passport.use(new LocalStrategy(...))findOne 密码比对 三种done语义调用下一关在/loginPOST 路由上用passport.authenticate(local)触发策略failureRedirect处理失败分支会话与持久化前置关卡express-session 序列化保证登录一次后续请求免验证安全加固后续关卡bcrypt哈希替换明文比对。核心参考文件Authentication Strategies 关卡文档本文主体Set up Passport、Serialization of a User Object、Implement the Serialization of a Passport User前置关卡How to Use Passport Strategies、Hashing Your Passwords后续关卡关卡顺序定义、所在超级块说明以上内容基于当前课程仓库中文档的原文与关卡顺序文件整理文中涉及的依赖版本passport-local~1.0.0、passport~0.4.1、express-session~1.17.1、mongodb~3.6.0、bcrypt~5.0.0均以课程模板package.json中的声明为准。【免费下载链接】freeCodeCampfreeCodeCamp.orgs open-source codebase and curriculum. Learn math, programming, and computer science for free.项目地址: https://gitcode.com/GitHub_Trending/fr/freeCodeCamp创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考