Using Credential Management API in JavaScript
The Credential Management API provides a standardized programmatic interface that enables web applications to securely store, retrieve, and manage user credentials directly through the browser. By bridging the gap between web applications and the browser’s built-in password manager, this API streamlines the authentication process, enables automatic sign-in, and eliminates the friction of traditional manual login forms.
Storing User Credentials
To store a user’s login information, you create a credential object
and pass it to the navigator.credentials.store() method
after a successful authentication event (such as a form submission).
For standard username and password authentication, the API provides
the PasswordCredential constructor.
// Function to store credentials after a successful login
async function saveUserCredentials(username, password, name) {
if ('credentials' in navigator && window.PasswordCredential) {
try {
const credential = new PasswordCredential({
id: username, // Unique user identifier (email, username)
password: password, // Plaintext password
name: name // Optional: Display name
});
// Prompt the browser to store or update the credential
await navigator.credentials.store(credential);
console.log('Credentials stored successfully.');
} catch (error) {
console.error('Failed to store credentials:', error);
}
}
}When navigator.credentials.store() is invoked, the
browser asks the user if they want to save or update their login details
in the browser’s password store.
Retrieving User Credentials
To authenticate a returning user without requiring manual input, use
the navigator.credentials.get() method. This queries the
browser’s credential storage for matching credentials.
// Function to retrieve stored credentials
async function getStoredCredentials() {
if ('credentials' in navigator) {
try {
const credential = await navigator.credentials.get({
password: true,
mediation: 'optional' // Options: 'silent', 'optional', 'required'
});
if (credential) {
// Send credential details to your backend for authentication
await authenticateWithBackend({
username: credential.id,
password: credential.password
});
} else {
console.log('No credentials returned or user dismissed the prompt.');
}
} catch (error) {
console.error('Error retrieving credentials:', error);
}
}
}Mediation Modes
The mediation option controls how the browser interacts
with the user during retrieval:
silent: Retrieves credentials only if no user interaction is required (auto-sign-in). If interaction is needed, it resolves tonull.optional: Attempts silent retrieval first; if multiple accounts exist, it prompts the user to select one.required: Always requires explicit user confirmation before returning credentials.
Handling Sign-Out
When a user explicitly logs out of an application, automatic sign-in
should be disabled to prevent the user from being immediately logged
back in on the next visit. Use
navigator.credentials.preventSilentAccess() during the
logout routine.
async function logoutUser() {
if ('credentials' in navigator) {
await navigator.credentials.preventSilentAccess();
}
// Proceed with standard session cleanup
}Calling this method ensures that the next time
navigator.credentials.get() runs, it will not log the user
in automatically without explicit user interaction.