Web Security

Understanding Authentication and Authorization in Web Apps: Complete 2024 Guide

David Chen
July 5, 2024
32,819 Views
18 min read
David Chen

David Chen

Security engineer with 12+ years of experience in web application security. OAuth contributor and security consultant for Fortune 500 companies.

Authentication and authorization form the foundation of web application security. In this comprehensive guide, we'll explore these critical concepts, their differences, implementation methods, and security best practices to protect your users and data in 2024.

Authentication vs Authorization: Key Differences

Authentication (AuthN) - Who Are You?

  • Verifies user identity (username/password, biometrics, etc.)
  • Answers the question: "Are you who you say you are?"
  • Typically happens first in the security process
  • Examples: Login forms, SSO, passwordless authentication

Authorization (AuthZ) - What Can You Do?

  • Determines permissions and access rights
  • Answers the question: "What are you allowed to do?"
  • Happens after successful authentication
  • Examples: Role-based access control (RBAC), permissions
Characteristic Authentication Authorization Purpose Verify identity Grant permissions When it occurs During login After authentication Methods Passwords, biometrics, 2FA Roles, permissions, policies Changes frequency Rarely (credentials) Often (permissions) Example Employee badge scan Access to specific rooms

"Authentication without authorization is useless - you know who someone is but don't control what they can do. Authorization without authentication is dangerous - you're granting access without verifying identity." - Security Principle

Authentication Methods

Modern web applications use various authentication methods with different security levels:

Password-Based

Traditional username/password combination. Requires strong password policies and secure storage (hashing).

Medium Security

Multi-Factor (MFA)

Combines two or more factors (knowledge, possession, inherence). Examples: SMS codes, authenticator apps, hardware tokens.

High Security

Biometric

Uses unique biological characteristics like fingerprints, facial recognition, or iris scans.

High Security

Single Sign-On (SSO)

Allows users to authenticate once and access multiple systems. Common protocols: SAML, OAuth, OpenID Connect.

Medium Security

Passwordless

Eliminates passwords using magic links, email codes, or WebAuthn standards.

High Security

Social Login

Authenticate using existing accounts from Google, Facebook, etc. Convenient but depends on third-party security.

Medium Security

Authorization Models

Different authorization models provide varying levels of access control granularity:

1. Role-Based Access Control (RBAC)

  • Users are assigned roles (Admin, Editor, Viewer)
  • Roles have predefined permissions
  • Simple to implement and manage
  • Common in enterprise applications
// Example RBAC check
if (user.role === 'admin') {
  // Grant admin access
} else if (user.role === 'editor') {
  // Grant editor access
}

2. Attribute-Based Access Control (ABAC)

  • Uses attributes (user, resource, environment) to make decisions
  • More flexible than RBAC
  • Complex to implement but powerful
  • Example: "Allow access if user is department manager AND it's weekday"

3. Permission-Based Access Control

  • Users have direct permissions (create_post, delete_user)
  • Can be combined with roles
  • Very granular control

4. Rule-Based Access Control

  • Uses custom rules to evaluate access
  • Often expressed in domain-specific language
  • Used in complex authorization systems
  • Example: "Allow access if resource.owner == user.id"

Authentication Protocols

Modern web applications use standardized protocols for secure authentication:

OAuth 2.0

Authorization framework for delegated access. Allows apps to obtain limited access to user accounts.

High Security

OpenID Connect

Identity layer built on OAuth 2.0. Provides authentication information (ID tokens).

High Security

SAML

XML-based standard for exchanging authentication and authorization data between parties.

High Security

JWT

JSON Web Tokens - Compact, URL-safe tokens that represent claims between parties.

Medium Security

OAuth 2.0 Flow Example

1

User Requests Access

User clicks "Login with Google" on your application

2

Authorization Request

Your app redirects to Google's authorization server with requested scopes

3

User Authentication

Google authenticates the user and obtains consent for requested permissions

4

Authorization Grant

Google sends authorization code back to your application

5

Token Exchange

Your app exchanges authorization code for access token (and optionally refresh token)

6

Access Protected Resources

Your app uses access token to make API requests on behalf of the user

Security Best Practices

Implement these security measures to protect your authentication and authorization systems:

Always Use HTTPS

Encrypt all authentication-related communications to prevent MITM attacks

Implement Rate Limiting

Prevent brute force attacks by limiting login attempts

Use Secure Password Storage

Always hash passwords with strong algorithms (Argon2, bcrypt, PBKDF2)

Enable Multi-Factor Authentication

Add an extra layer of security beyond passwords

Implement Proper Session Management

Use secure, HttpOnly, SameSite cookies and short-lived sessions

Follow Principle of Least Privilege

Grant only the minimum permissions necessary

Regularly Audit Permissions

Review and remove unnecessary access rights

Validate All Inputs

Sanitize and validate all authentication-related inputs

Common Security Vulnerabilities

Be aware of these common authentication and authorization vulnerabilities:

1. Broken Authentication

  • Weak password policies
  • Poor session management
  • Exposure of credentials in URLs
  • Failure to invalidate sessions after logout

2. Broken Access Control

  • Insecure direct object references (IDOR)
  • Missing function-level access control
  • Elevation of privilege
  • Metadata manipulation (JWT, cookies)

3. Security Misconfiguration

  • Default accounts and passwords
  • Verbose error messages
  • Unnecessary features enabled
  • Outdated dependencies

4. Injection Flaws

  • SQL injection in authentication forms
  • LDAP injection
  • Template injection

Implementation Examples

1. Secure Password Hashing in Node.js

// Using bcrypt for password hashing
const bcrypt = require('bcrypt');
const saltRounds = 12;

async function hashPassword(password) {
  return await bcrypt.hash(password, saltRounds);
}

async function verifyPassword(password, hash) {
  return await bcrypt.compare(password, hash);
}

// Usage
const hashedPassword = await hashPassword('user_password');
const isMatch = await verifyPassword('input_password', hashedPassword);

2. JWT Authentication Middleware

// Express middleware for JWT authentication
const jwt = require('jsonwebtoken');

function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  
  if (!token) return res.sendStatus(401);
  
  jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

// Protected route
app.get('/api/protected', authenticateToken, (req, res) => {
  res.json({ message: 'Protected data', user: req.user });
});

3. Role-Based Authorization Middleware

// Express middleware for role-based authorization
function authorize(roles = []) {
  return (req, res, next) => {
    if (!req.user) return res.sendStatus(401);
    
    if (roles.length && !roles.includes(req.user.role)) {
      return res.sendStatus(403);
    }
    
    next();
  };
}
// Admin-only route
app.get('/api/admin', 
  authenticateToken, 
  authorize(['admin']), 
  (req, res) => {
    res.json({ message: 'Admin dashboard' });
  }
);

Mastering Web App Security

Proper authentication and authorization implementation is critical for web application security. Key takeaways:

  • Always verify before trusting: Authentication must come before authorization
  • Use modern standards: Implement OAuth 2.0, OpenID Connect, and JWT correctly
  • Follow security best practices: HTTPS, rate limiting, secure password storage
  • Regularly audit: Continuously review your security measures
  • Stay updated: Security threats evolve - keep your knowledge current

By implementing robust authentication and authorization, you protect both your users and your application from security breaches.

Enroll in Web Security Course