← Back to Node.js Course | Chapter 8: Working with APIs | Lesson 5 of 7

Authentication basics

Authentication proves who the caller is; common choices are API keys, sessions and tokens.

In this page:

  1. Authentication basics

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

javascript
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
  1. Storing plain passwords
  2. Putting secrets in source code
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.