用户注册与登录
构建用户注册和登录功能,包括密码哈希处理与凭据安全存储。
用户注册与登录 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 1 节课,共 6 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 6 节课。
本课时的部分内容尚未翻译,以英文显示。
Welcome to User Authentication
User authentication is how we verify who a user is. It's a critical part of almost any application that handles personal data or restricted features.
- Why it matters: Protects user accounts and sensitive information.
- What we'll cover: Building registration and login flows from scratch.
The User Registration Flow
Registering a new user involves several steps to create a new account:
- User provides credentials (e.g., username, password, email).
- Input data is validated (e.g., strong password, unique email).
- The password is hashed for security.
- New user data (including the hashed password) is saved to the database.
Why Hash Passwords?
Storing passwords in plain text is a huge security risk! If your database is breached, all user passwords would be exposed.
Hashing transforms a password into a fixed-size, unreadable string. It's a one-way process, meaning you can't easily get the original password back from the hash.
We use libraries like bcrypt in Node.js for robust password hashing, which also adds a 'salt' to prevent common attacks.
Hashing Passwords with bcrypt
bcrypt is a popular library for securely hashing passwords. It's computationally intensive, making brute-force attacks harder.
Try running this example to see a password hashed:
const bcrypt = require('bcrypt');
const password = "mySecretP@ssword";
const saltRounds = 10; // Cost factor for hashing (higher is slower/more secure)
async function hashPassword() {
try {
const hashedPassword = await bcrypt.hash(password, saltRounds);
console.log("Original: " + password);
console.log("Hashed: " + hashedPassword);
} catch (error) {
console.error("Error hashing:" + error.message);
}
}
hashPassword();
Storing Hashed Credentials
After hashing, only the hashed password should be stored in your database, along with other user details like their email or username.
- NEVER store plain-text passwords.
- The hash is unique for each password, even if the original passwords are the same (thanks to salting).
- This hash is what you'll use for comparison during login.
The User Login Flow
When a user tries to log in, your application follows these steps:
- User provides their username/email and password.
- Application retrieves the user's record (including their stored hashed password) from the database based on the username/email.
- The provided password is hashed and compared against the stored hash.
- If they match, the user is authenticated, and a session or token is created.
Verifying Passwords with bcrypt
To check if a user's provided password matches the stored hash, we use bcrypt.compare(). It performs the hashing and comparison securely.
Run this code to see password comparison in action:
const bcrypt = require('bcrypt');
// This hash would typically come from your database
const storedHash = "$2b$10$w090/qB2k6n0Y7o8p9q.u.0Z1X2Y3Z4A5B6C7D8E9F0G1H2I3J4K5L6M7N8O9P0Q1R";
const passwordAttempt = "mySecretP@ssword";
const wrongAttempt = "incorrectPassword";
async function comparePasswords() {
try {
const isMatch = await bcrypt.compare(passwordAttempt, storedHash);
console.log(`'${passwordAttempt}' matches: ${isMatch}`);
const isWrongMatch = await bcrypt.compare(wrongAttempt, storedHash);
console.log(`'${wrongAttempt}' matches: ${isWrongMatch}`);
} catch (error) {
console.error("Error comparing:" + error.message);
}
}
comparePasswords();
Secure Credential Storage Practices
Beyond just hashing passwords, other credentials need protection:
- API Keys & Database URLs: Store these in environment variables (e.g.,
.envfiles), not directly in your code. - Sensitive User Data: Encrypt any highly sensitive data at rest in your database.
- Regular Updates: Keep your hashing libraries and dependencies up-to-date.
Handling Authentication Errors
When registration or login fails, provide helpful but generic error messages to the user. This prevents revealing too much information to potential attackers.
- Instead of 'User not found', say 'Invalid credentials'.
- Instead of 'Password incorrect', also say 'Invalid credentials'.
- Log detailed errors on the server side for debugging, but don't expose them to the client.
Quick Check: Password Hashing
Test your understanding of why password hashing is essential for security.
Recap: Registration & Login
In this lesson, you learned the fundamental steps for user registration and login:
- We covered the importance of password hashing using
bcryptto protect sensitive user data. - You saw how to implement both the hashing for registration and the comparison for login.
- We also touched on best practices for secure credential storage and handling authentication errors gracefully.
Next, we'll dive into implementing stateless authentication using JSON Web Tokens (JWTs).
常见问题解答
「用户注册与登录」课时是免费的吗?
是的 — 「用户注册与登录」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 6 节课。
「用户注册与登录」这节课中我会学到什么?
构建用户注册和登录功能,包括密码哈希处理与凭据安全存储。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 6 节。
「用户注册与登录」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。