>本文探討了均值堆棧應用程序中的用戶身份驗證,採用通用體系結構:與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
<code class="language-javascript">var userSchema = new mongoose.Schema({ email: { type: String, unique: true, required: true }, name: { type: String, required: true }, hash: String, salt: String });</code>
密碼哈希和鹽鹽:
和setPassword
>方法,利用node.js的validPassword
模塊,處理安全密碼管理而無需直接存儲密碼。 crypto
>
<code class="language-javascript">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; };</code>
jwt生成:
>模塊來創建JWT。 generateJwt
記住,請記住將您的秘密安全地存儲為環境變量,而不是直接在代碼中。
jsonwebtoken
PASSPORT.JS配置:
<code class="language-javascript">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"); };</code>passport.js簡化了Express中的身份驗證。
文件定義了本地策略:
api端點和身份驗證:/api/config/passport.js
<code class="language-javascript">passport.use(new LocalStrategy({ usernameField: 'email' }, function(username, password, done) { User.findOne({ email: username }, function(err, user) { // ... (error handling and password verification logic) ... }); }));</code>
文件定義了API路由,包括使用的JWT身份驗證的中間件:
/api/routes/index.js
角身份驗證服務:express-jwt
<code class="language-javascript">var auth = jwt({ secret: 'MY_SECRET', userProperty: 'payload' }); router.get('/profile', auth, ctrlProfile.profileRead);</code>)管理JWT存儲(LocalStorage),檢索,刪除,API調用,登錄狀態檢查和用戶詳細信息從JWT。
角路線保護:
)保護authentication.service.ts
路線,確保只登錄的用戶才能訪問它。
結論:
常見問題(常見問題解答):auth-guard.service.ts
(原始常見問題解答已經非常全面且寫得很好。我不會在這裡重複這些問題,因為加上它們會使他們的回答過長。)/profile
以上是用均值堆棧的用戶身份驗證的詳細內容。更多資訊請關注PHP中文網其他相關文章!