Back to Backend & APIs

Module 5: Authentication & Security

Implement secure authentication and protect your APIs from common vulnerabilities.

Authentication vs Authorization

Authentication is proving who you are (like showing your ID). Authorization is proving what you're allowed to do (like having a VIP pass). Both are critical for API security.

🔐 Authentication Methods:

  • Session-based: Server stores session data
  • Token-based (JWT): Stateless, scalable
  • OAuth 2.0: Third-party authentication
  • API Keys: Simple, for service-to-service
  • Biometric: Fingerprint, face recognition

JWT (JSON Web Tokens)

JWT Implementation:

const jwt = require('jsonwebtoken');

const bcrypt = require('bcrypt');

// Register user

app.post('/register', async (req, res) => {

const { email, password } = req.body;

// Hash password

const hashedPassword = await bcrypt.hash(password, 10);

// Save user to database

const user = await User.create({ email, password: hashedPassword });

res.status(201).json({ message: 'User created' });

});

// Login

app.post('/login', async (req, res) => {

const { email, password } = req.body;

// Find user

const user = await User.findOne({ email });

if (!user) {

return res.status(401).json({ error: 'Invalid credentials' });

}

// Verify password

const isValid = await bcrypt.compare(password, user.password);

if (!isValid) {

return res.status(401).json({ error: 'Invalid credentials' });

}

// Generate JWT

const token = jwt.sign(

{ userId: user.id, email: user.email },

process.env.JWT_SECRET,

{ expiresIn: '24h' }

);

res.json({ token });

});

// Auth middleware

const authenticate = (req, res, next) => {

const token = req.headers.authorization?.split(' ')[1];

if (!token) {

return res.status(401).json({ error: 'No token provided' });

}

try {

const decoded = jwt.verify(token, process.env.JWT_SECRET);

req.user = decoded;

next();

} catch (err) {

res.status(401).json({ error: 'Invalid token' });

}

};

// Protected route

app.get('/profile', authenticate, (req, res) => {

res.json({ user: req.user });

});

OAuth 2.0 & Social Login

Passport.js with Google OAuth:

const passport = require('passport');

const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({

clientID: process.env.GOOGLE_CLIENT_ID,

clientSecret: process.env.GOOGLE_CLIENT_SECRET,

callbackURL: '/auth/google/callback'

},

async (accessToken, refreshToken, profile, done) => {

// Find or create user

let user = await User.findOne({ googleId: profile.id });

if (!user) {

user = await User.create({

googleId: profile.id,

email: profile.emails[0].value,

name: profile.displayName

});

}

done(null, user);

}));

// Routes

app.get('/auth/google',

passport.authenticate('google', { scope: ['profile', 'email'] })

);

app.get('/auth/google/callback',

passport.authenticate('google'),

(req, res) => res.redirect('/dashboard')

);

API Security Best Practices

1. HTTPS Only

Always use HTTPS to encrypt data in transit.

2. Rate Limiting

const rateLimit = require('express-rate-limit');

const limiter = rateLimit({

windowMs: 15 * 60 * 1000, // 15 minutes

max: 100 // limit each IP to 100 requests per windowMs

});

app.use('/api/', limiter);

3. Input Validation

const { body, validationResult } = require('express-validator');

app.post('/users',

body('email').isEmail(),

body('password').isLength({ min: 8 }),

(req, res) => {

const errors = validationResult(req);

if (!errors.isEmpty()) {

return res.status(400).json({ errors: errors.array() });

}

// Process request...

}

);

4. CORS Configuration

const cors = require('cors');

app.use(cors({

origin: ['https://yourdomain.com'],

credentials: true

}));

5. Helmet.js (Security Headers)

const helmet = require('helmet');

app.use(helmet());

6. SQL Injection Prevention

Use parameterized queries or ORMs.

// Bad - SQL Injection vulnerable

db.query(`SELECT * FROM users WHERE id = ${userId} `);

// Good - Parameterized query

db.query('SELECT * FROM users WHERE id = ?', [userId]);

📚 Module Summary

You've mastered authentication and security:

  • ✓ JWT authentication
  • ✓ Password hashing with bcrypt
  • ✓ OAuth 2.0 and social login
  • ✓ Rate limiting and CORS
  • ✓ Input validation
  • ✓ Security best practices

Next: Learn NestJS framework!