Express.js Authentication Basics
Imagine you're at a private club. Not everyone can just walk in – you need to show your membership card at the door. The bouncer checks if you're a member and then lets you in. This is exactly how **authentication** works in web applications!
What is Authentication?
Authentication is the process of verifying who a user is. It answers the question "Are you who you claim to be?" This is typically done through:
- Username/Password (most common)
- Social login (Google, Facebook, GitHub)
- Biometrics (fingerprint, face recognition)
- Two-factor authentication (2FA)
Authentication is like showing your ID. Authorization (which comes after) is like what you're allowed to do once you're in.
Authentication vs Authorization
| Authentication | Authorization |
|---|---|
| Verifies identity ("Who are you?") | Verifies permissions ("What can you do?") |
| Login process | Access control (admin, user, guest) |
| Done first | Done after authentication |
Basic Authentication Flow
- User submits login form (username/password).
- Server checks credentials against database.
- If valid, server creates a session or token.
- Server sends session ID (cookie) or token to client.
- Client includes this credential in subsequent requests.
Simple Password Authentication (Without Hashing – DON'T DO THIS!)
<!-- ❌ NEVER store plain text passwords! -->app.post('/login', (req, res) => { const { username, password } = req.body; <!-- Query database for user --> const user = findUserByUsername(username); if (user && user.password === password) { <!-- Success – NEVER do this! --> }});Password Hashing with bcrypt
Never store plain text passwords! Use `bcrypt` to hash passwords.
npm install bcryptconst bcrypt = require('bcrypt');const saltRounds = 10;
<!-- Register: hash password before saving -->app.post('/register', async (req, res) => { try { const { username, password } = req.body; <!-- Hash the password --> const hashedPassword = await bcrypt.hash(password, saltRounds); <!-- Save user with hashedPassword to database --> <!-- ... --> res.status(201).json({ message: 'User created' }); } catch (err) { res.status(500).json({ error: err.message }); }});
<!-- Login: compare password with hash -->app.post('/login', async (req, res) => { try { const { username, password } = req.body; <!-- Get user from database --> const user = await findUserByUsername(username); if (!user) { return res.status(401).json({ error: 'Invalid credentials' }); } <!-- Compare password with stored hash --> const match = await bcrypt.compare(password, user.password); if (match) { <!-- Successful login – create session/token --> res.json({ message: 'Login successful' }); } else { res.status(401).json({ error: 'Invalid credentials' }); } } catch (err) { res.status(500).json({ error: err.message }); }});Session-Based Authentication
Using `express-session` (covered in Group 4) is one way to maintain login state.
app.post('/login', async (req, res) => { <!-- After verifying credentials --> req.session.userId = user.id; req.session.isLoggedIn = true; res.json({ message: 'Logged in' });});
<!-- Protect routes with middleware -->const requireAuth = (req, res, next) => { if (!req.session.userId) { return res.status(401).json({ error: 'Not authenticated' }); } next();};
app.get('/profile', requireAuth, (req, res) => { <!-- Show profile -->});Two Minute Drill
- Authentication verifies identity ("Who are you?").
- Authorization controls access ("What can you do?").
- Never store plain text passwords – always hash with bcrypt.
- Use `bcrypt.hash()` for registration and `bcrypt.compare()` for login.
- Sessions or tokens maintain authentication state across requests.
Need more clarification?
Drop us an email at career@quipoinfotech.com
