Hack Frontend Community

What is the Difference Between Authorization and Authentication?

What is the Difference Between Authorization and Authentication?

Authentication and Authorization are two different but interconnected security processes in web applications.


Authentication

Authentication is the process of verifying user identity. The system determines who you are.

Key Characteristics

  • Answers the question: "Who are you?"
  • Verifies credentials (login/password, token, biometrics)
  • Happens before authorization
  • Result: user is identified or not

Authentication Examples

// Simple authentication example
async function authenticate(email, password) {
  const response = await fetch('/api/auth/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password })
  });
  
  if (response.ok) {
    const { token } = await response.json();
    // Save token for subsequent requests
    localStorage.setItem('authToken', token);
    return true;
  }
  
  return false;
}

Authentication Methods

  1. Username and Password — classic approach
  2. OAuth 2.0 — login via Google, Facebook, etc.
  3. JWT Tokens — digitally signed tokens
  4. Biometrics — fingerprint, Face ID
  5. Two-Factor Authentication (2FA) — additional code from SMS or app
  6. Magic Links — login link sent via email

Authorization

Authorization is the process of verifying access rights. The system determines what you are allowed to do.

Key Characteristics

  • Answers the question: "What are you allowed to do?"
  • Checks user permissions and roles
  • Happens after authentication
  • Result: access granted or denied

Authorization Examples

// Access control check example
function checkAuthorization(user, resource, action) {
  // Check user role
  if (action === 'delete' && user.role !== 'admin') {
    throw new Error('Insufficient permissions to delete');
  }
  
  // Check resource ownership
  if (action === 'edit' && resource.ownerId !== user.id) {
    throw new Error('You can only edit your own resources');
  }
  
  return true;
}

// Middleware to protect routes
function requireAdmin(req, res, next) {
  if (req.user?.role !== 'admin') {
    return res.status(403).json({ error: 'Access denied' });
  }
  next();
}

Authorization Models

  1. Role-Based Access Control (RBAC) — based on roles (admin, user, moderator)
  2. Attribute-Based Access Control (ABAC) — based on user attributes
  3. Access Control Lists (ACL) — access lists for each resource
  4. Policy-Based Access Control (PBAC) — based on security policies

Key Differences

CriteriaAuthenticationAuthorization
Question"Who are you?""What can you do?"
PurposeVerify identityVerify permissions
OrderFirst stepSecond step
DataLogin, password, tokenRoles, permissions, policies
ResultLogin successful / deniedAccess granted / denied
HTTP Status401 Unauthorized403 Forbidden
ExampleSystem loginAdmin panel access

Practical Example

// 1. AUTHENTICATION — verify who the user is
app.post('/api/auth/login', async (req, res) => {
  const { email, password } = req.body;
  
  const user = await User.findOne({ email });
  if (!user || !await user.comparePassword(password)) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }
  
  const token = generateJWT(user);
  res.json({ token, user: { id: user.id, role: user.role } });
});

// 2. AUTHORIZATION — verify access permissions
app.delete('/api/posts/:id', authenticateToken, async (req, res) => {
  const post = await Post.findById(req.params.id);
  
  // Check permissions: only author or admin can delete
  if (post.authorId !== req.user.id && req.user.role !== 'admin') {
    return res.status(403).json({ error: 'Insufficient permissions' });
  }
  
  await post.delete();
  res.json({ success: true });
});

// Authentication middleware
function authenticateToken(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({ error: 'Authentication required' });
  }
  
  try {
    req.user = verifyJWT(token);
    next();
  } catch (error) {
    return res.status(401).json({ error: 'Invalid token' });
  }
}

Process Flow

┌─────────────────┐
│      User       │
└────────┬────────┘
┌─────────────────────────┐
│   1. AUTHENTICATION     │
│   "Who are you?"        │
│   Login + Password      │
└────────┬────────────────┘
    ✓ Success
┌─────────────────────────┐
│   2. AUTHORIZATION      │
│   "What can you do?"    │
│   Permission check      │
└────────┬────────────────┘
    ✓ Access granted
┌─────────────────────────┐
│   Access to resource    │
└─────────────────────────┘

HTTP Error Codes

401 Unauthorized — Authentication Error

  • User is not authenticated
  • Token is missing or invalid
  • Invalid credentials
// 401 Example
res.status(401).json({ error: 'Login required' });

403 Forbidden — Authorization Error

  • User is authenticated but lacks permissions
  • Insufficient rights to perform action
// 403 Example
res.status(403).json({ error: 'Access denied' });

Real-Life Examples

Authentication

  • Logging into Gmail with username and password
  • Unlocking phone with fingerprint
  • Showing passport at border control

Authorization

  • Admin panel access only for administrators
  • Editing only your own posts on social media
  • Viewing private files only by owner

Interview Tips

  1. Remember the order: authentication first, then authorization
  2. Distinguish HTTP codes: 401 for authentication, 403 for authorization
  3. Provide examples: JWT for authentication, RBAC for authorization
  4. Understand the connection: no authorization without authentication
  5. Know the methods: OAuth, JWT, 2FA for authentication; RBAC, ACL for authorization

Summary

  • Authentication — identity verification ("Who are you?")
  • Authorization — permission verification ("What can you do?")
  • Authentication always happens before authorization
  • 401 — authentication error, 403 — authorization error
  • Both processes are critical for application security