Authentication basics
Authentication proves who the caller is; common choices are API keys, sessions and tokens.
In this page:
Authentication basics
Never store plain passwords; hash with bcrypt or scrypt. After login, issue a session cookie or a signed token such as a JWT and verify it on each request. Send secrets only over HTTPS. Authorization, deciding what a user may do, is a separate step.
Note:
Node's built-in crypto.scrypt can hash passwords without extra packages.
Example: Authentication basics
const crypto = require("crypto");
function hash(password, salt = crypto.randomBytes(8).toString("hex")) {
return salt + ":" + crypto.scryptSync(password, salt, 16).toString("hex");
}
function verify(password, stored) {
const [salt] = stored.split(":");
return hash(password, salt) === stored;
}
const stored = hash("s3cret");
console.log("right:", verify("s3cret", stored));
console.log("wrong:", verify("nope", stored));
// Output:
// right: true
// wrong: false
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Storing plain passwords
- Putting secrets in source code
- Confusing authentication with authorization
Chapter Summary
- Hash passwords
- Tokens or sessions identify users
- Use HTTPS
- Authorization is separate
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: