>本文探讨了均值堆栈应用程序中的用户身份验证,采用通用体系结构:与node.js,express.js和基于mongodb的and appi相互作用的角度单页应用程序。 我们将介绍安全用户管理的关键方面。
核心身份验证挑战:
这个过程需要解决几个关键点:
>在进行代码之前,让我们检查高级身份验证流:
crypto
Angular应用具有四个基本页面:
主页 寄存器
登录
profile(仅登录用户仅访问)
/api/register
(post):用户注册。/api/login
(post):用户登录。/api/profile/:USERID
>(get):检索用户配置文件详细信息(受保护)。> mongodb schema(mongoose):
中的简单用户架构定义/api/models/users.js
,email
,name
和hash
>字段。 salt
字段是唯一的。email
var userSchema = new mongoose.Schema({ email: { type: String, unique: true, required: true }, name: { type: String, required: true }, hash: String, salt: String });
密码哈希和盐盐:
和setPassword
>方法,利用node.js的validPassword
模块,处理安全密码管理而无需直接存储密码。crypto
>
userSchema.methods.setPassword = function(password) { this.salt = crypto.randomBytes(16).toString('hex'); this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha512').toString('hex'); }; userSchema.methods.validPassword = function(password) { var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha512').toString('hex'); return this.hash === hash; };
jwt生成:
>模块来创建JWT。 generateJwt
记住,请记住将您的秘密安全地存储为环境变量,而不是直接在代码中。
jsonwebtoken
PASSPORT.JS配置:
userSchema.methods.generateJwt = function() { var expiry = new Date(); expiry.setDate(expiry.getDate() + 7); return jwt.sign({ _id: this._id, email: this.email, name: this.name, exp: parseInt(expiry.getTime() / 1000), }, "MY_SECRET"); };
文件定义了本地策略:
api端点和身份验证:/api/config/passport.js
passport.use(new LocalStrategy({ usernameField: 'email' }, function(username, password, done) { User.findOne({ email: username }, function(err, user) { // ... (error handling and password verification logic) ... }); }));
文件定义了API路由,包括使用的JWT身份验证的中间件:
/api/routes/index.js
角身份验证服务:express-jwt
var auth = jwt({ secret: 'MY_SECRET', userProperty: 'payload' }); router.get('/profile', auth, ctrlProfile.profileRead);
角路线保护:
)保护authentication.service.ts
路线,确保只登录的用户才能访问它。
结论:
常见问题(常见问题解答):auth-guard.service.ts
(原始常见问题解答已经非常全面且写得很好。我不会在这里重复这些问题,因为加上它们会使他们的回答过长。)/profile
以上是用均值堆栈的用户身份验证的详细内容。更多信息请关注PHP中文网其他相关文章!