Authentication Basics

Authentication is the process of verifying a user's identity to grant access to a system or application. In JavaScript, authentication usually involves handling user credentials and validating them securely.

Illustration of Authentication Basics
Illustration of Authentication Basics

💡 Key Concept

Authentication differs from authorization: Authentication confirms who you are, while authorization determines what you can access.

Common Authentication Methods

  • Username and Password: The most basic form, users provide credentials which get validated.
  • Token-based Authentication: After login, the server issues a token (like JWT) used to authenticate subsequent requests.
  • OAuth: Allows users to log in using third-party providers (Google, Facebook).

Basic Authentication with JavaScript

In a simple JavaScript app, authentication typically involves:

  • Collecting user input via a form
  • Sending credentials securely to a backend
  • Receiving a response indicating success or failure
  • Storing authentication tokens (e.g., in localStorage or cookies) for session management

📌 Deep Dive: Storing and Using a Token

JAVASCRIPT
// After successful login, store token
const token = 'abc123token';
localStorage.setItem('authToken', token);

// Use token for authenticated requests
fetch('/api/data', {
  headers: {
    'Authorization': `Bearer ${localStorage.getItem('authToken')}`
  }
})
.then(res => res.json())
.then(data => console.log(data));
Output
Data from protected API endpoint logged to console

⚠️ Security Reminder

Never store sensitive tokens in plain cookies or localStorage without proper security measures (e.g., HttpOnly cookies, secure flags) to avoid XSS or CSRF attacks.

Authentication vs Authorization
AspectDescription
AuthenticationVerifies user identity (e.g., login with username/password)
AuthorizationControls access rights after authentication (e.g., admin privileges)

Summary

  • Authentication is verifying who the user is.
  • JavaScript apps typically handle authentication by communicating with backend services.
  • Tokens like JWT are common for managing sessions on the client.
  • Security is critical when handling authentication data.