Blog | G5 Cyber Security

Fast Login: Async vs Sync Authentication

TL;DR

Synchronous authentication blocks your website until the login is complete, making it feel slow. Asynchronous authentication lets users continue browsing while logging in, improving speed and user experience. This guide explains how to choose and implement each method.

Understanding Authentication Types

Authentication verifies a user’s identity. There are two main ways this happens:

1. Synchronous Authentication – How It Works

With synchronous authentication, when a user tries to log in:

  1. The browser sends login details (username/password) to the server.
  2. The server checks these details against its database.
  3. Until the server confirms or denies access, the browser is blocked – often showing a loading message.
  4. Once authentication completes, the user is either granted access or shown an error.

Example (PHP):

Pros: Simple to implement.

Cons: Slow, poor user experience if authentication takes time (e.g., database issues).

2. Asynchronous Authentication – How It Works

Asynchronous authentication uses techniques like JavaScript and AJAX to avoid blocking the browser:

  1. The browser sends login details to the server using an asynchronous request (e.g., using fetch or XMLHttpRequest).
  2. The server starts the authentication process in the background.
  3. The browser receives a response immediately, often confirming that the request has been received.
  4. The user can continue browsing while the server authenticates.
  5. Once authentication is complete, the server updates the user’s status (e.g., using cookies or local storage) and potentially redirects them to a secure area.

Example (JavaScript with fetch):

async function login() {
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;

  try {
    const response = await fetch('/login', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({ username, password })
    });

    if (response.ok) {
      const data = await response.json();
      if (data.success) {
        // Update UI to show logged-in state
        console.log('Login successful!');
      } else {
        alert(data.message);
      }
    } else {
      alert('Login failed: ' + response.status);
    }
  } catch (error) {
    console.error('Error during login:', error);
    alert('An unexpected error occurred.');
  }
}

Pros: Faster, better user experience.

Cons: More complex to implement; requires handling background processes and updating the UI accordingly. Security considerations are more important (e.g., protecting against CSRF attacks).

3. Choosing Between Synchronous and Asynchronous

4. Security Considerations

Exit mobile version