2 min read

Credential Management API

The Credential Management API provides a programmatic interface to the browser's credential manager. It allows websites to store and retrieve user credentials (passwords or federated login details) to enable seamless sign-in experiences.

1. The Concept

Instead of managing cookies or local storage for sessions manually and asking users to type passwords repeatedly, this API lets the browser handle the storage. If a user returns to your site, you can request their credentials and automatically log them in.

2. Storing Credentials

When a user signs up or logs in successfully, you should store their credential.

async function storeCredential(username, password) {
  try {
    // Create a PasswordCredential object
    const cred = new PasswordCredential({
      id: username,
      password: password,
      name: username, // Optional: Display name
      iconURL: 'https://example.com/icon.png' // Optional
    });

    // Store it
    await navigator.credentials.store(cred);
    console.log('Credential stored!');
  } catch (err) {
    console.error('Error storing credential:', err);
  }
}

3. Retrieving Credentials

When the page loads, you can check if there's a stored credential to auto-login the user.

async function autoLogin() {
  try {
    const cred = await navigator.credentials.get({
      password: true,
      // federated: { providers: ['https://accounts.google.com'] }, // For federated login
      mediation: 'optional' // 'silent', 'optional', or 'required'
    });

    if (cred) {
      console.log('Got credential for:', cred.id);

      // Send cred.id and cred.password to your server to verify and create session
      // loginWithServer(cred);
    }
  } catch (err) {
    console.error('Error retrieving credential:', err);
  }
}

Mediation Modes

  • silent: The browser tries to return a credential without showing any UI. If user intervention is required, it returns null.
  • optional: If a single credential exists, it might auto-return it. If multiple exist, it might show a chooser.
  • required: Forces the browser to show a chooser UI.

4. Preventing Silent Access

When a user explicitly logs out, you should ensure they aren't immediately auto-logged back in via mediation: 'silent' on the next page load.

function logout() {
  // 1. Clear server session
  // ...

  // 2. Prevent silent access
  navigator.credentials.preventSilentAccess();

  console.log('Logged out and silent access disabled.');
}

5. Credential Types

programming/javascript/vanilla/javascript programming/javascript/vanilla/web-authentication-api programming/javascript/vanilla/promises-async-await