Credential Management Level 1

Editor’s Draft,

More details about this document
This version:
https://w3c.github.io/webappsec-credential-management/
Latest published version:
https://www.w3.org/TR/credential-management-1/
Previous Versions:
Version History:
https://github.com/w3c/webappsec-credential-management/commits/main/index.src.html
Feedback:
[email protected] with subject line “[credential-management] … message topic …” (archives)
GitHub
Editors:
(Google Inc.)
(Apple Inc.)
Former Editors:
(Google Inc.)
(Google Inc.)
Participate:
File an issue (open issues)

Abstract

This specification describes an imperative API enabling a website to request a user’s credentials from a user agent, and to help the user agent correctly store user credentials for future use.

Status of this document

This is a public copy of the editors’ draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don’t cite this document other than as work in progress.

Changes to this document may be tracked at https://github.com/w3c/webappsec.

The (archived) public mailing list [email protected] (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “credential-management” in the subject, preferably like this: “[credential-management] …summary of comment…

This document was produced by the Web Application Security Working Group.

This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 03 November 2023 W3C Process Document.

1. Introduction

This section is not normative.

Signing into websites is more difficult than it should be. The user agent is in a unique position to improve the experience in a number of ways, and most modern user agents have recognized this by providing some measure of credential management natively in the browser. For example, users can save usernames and passwords for websites; those credentials are later autofilled into sign-in forms, albeit with varying degrees of success.

The autocomplete attribute offers a declarative mechanism by which websites can work with user agents to improve the latter’s ability to detect and fill sign-in forms by marking specific fields as "username" or "password", and user agents implement a wide variety of detection heuristics to work with websites which haven’t taken the time to provide this detail in markup.

While this combination of heuristic and declarative detection works relatively well, the status quo leaves some large gaps where detection is problematic. Sites with uncommon sign-in mechanisms (submitting credentials via XMLHttpRequest [XMLHTTPREQUEST], for instance) are difficult to reliably detect, as is the increasingly common case in which users wish to authenticate themselves using a federated identity provider. Allowing websites to more directly interact with the user agent’s credential manager would allow the credential manager to be more accurate on the one hand, and to assist users with federated sign-in on the other.

These use cases are explored in more detail in § 1.1 Use Cases and in Credential Management: Use Cases and Requirements; this specification attempts to address many of the requirements that document outlines by defining a Credential Manager API which a website can use to request credentials for a user, and to ask the user agent to persist credentials when a user signs in successfully.

Note: The API defined here is intentionally small and simple: it does not intend to provide authentication in and of itself, but is limited to providing an interface to the existing credential managers implemented by existing user agents. That functionality is valuable right now, without significant effort on the part of either vendors or authors. There’s certainly quite a bit more which could be done, of course. See § 9 Future Work for some thoughts we’ve punted for now, but which could be explored in future iterations of this API.

1.1. Use Cases

Modern user agents generally offer users the capability to save passwords when signing into a website, and likewise offer the capability to fill those passwords into sign-in forms fully- or semi-automatically when users return to a website. From the perspective of a website, this behavior is completely invisible: the website doesn’t know that passwords have been stored, and it isn’t notified that passwords have been filled. This is both good and bad. On the one hand, a user agent’s password manager works regardless of whether or not a site cooperates, which is excellent for users. On the other, the password managers' behaviors are a fragile and proprietary hodgepodge of heuristics meant to detect and fill sign-in forms, password change forms, etc.

A few problems with the status quo stand out as being particularly noteworthy:

2. Core API

From a developer’s perspective, a credential is an object which allows a developer to make an authentication decision for a particular action. This section defines a generic and extensible Credential interface which serves as a base class for credentials defined in this and other documents, along with a set of APIs hanging off of navigator.credentials.* which enable developers to obtain them.

Various credential types are each represented to JavaScript as an interface which inherits, either directly or indirectly, from the Credential interface. This document defines two such interfaces, PasswordCredential and FederatedCredential. Other specifications, for example [WEBAUTHN], define other credential types.

A credential is effective for a particular origin if it is accepted as authentication on that origin. Even if a credential is effective at a particular point in time, the UA can’t assume that the same credential will be effective at any future time, for a couple reasons:

  1. A password credential may stop being effective if the account holder changes their password.

  2. A credential made from a token received over SMS is likely to only be effective for a single use.

Single-use credentials are generated by a credential source, which could be a private key, access to a federated account, the ability to receive SMS messages at a particular phone number, or something else. Credential sources are not exposed to Javascript or explicitly represented in this specification. To unify the model, we consider a password to be a credential source on its own, which is simply copied to create password credentials.

Even though the UA can’t assume that an effective credential will still be effective if used a second time, or that a credential source that has generated an effective credential will be able to generate a second effective credential in the future, the second is more likely than the first. By recording (with store()) which credentials have been effective in the past, the UA has a better chance of offering effective credential sources to the user in the future.

2.1. Infrastructure

User agents MUST internally provide a credential store, which is a vendor-specific, opaque storage mechanism to record which credentials have been effective. It offers the following capabilities for credential access and persistence:

  1. Store a credential for later retrieval. This accepts a credential, and inserts it into the credential store.

  2. Retrieve a list of credentials. This accepts an arbitrary filter, and returns a set of credentials that match the filter.

  3. Modify a credential. This accepts a credential, and overwrites the state of an existing credential in the credential store.

Additionally, the credential store should maintain a prevent silent access flag for origins (which is set to true unless otherwise specified). An origin requires user mediation if its flag is set to true.

Note: The importance of user mediation is discussed in more detail in § 5 User Mediation.

Note: The credential store is an internal implementation detail of a user agent’s implementation of the API specified in this document, and is not exposed to the web directly. More capabilities may be specified by other documents in support of specific credential types.

This document depends on the Infra Standard for a number of foundational concepts used in its algorithms and prose [INFRA].

Each environment settings object has an associated active credential types, a set which is initially empty.

2.1.1. Infrastructure Algorithms

2.1.1.1. Same-Origin with its Ancestors

An environment settings object (settings) is same-origin with its ancestors if the following algorithm returns true:

  1. If settings’s relevant global object has no associated Document, return false.

  2. Let document be settingsrelevant global object's associated Document.

  3. If document has no browsing context, return false.

  4. Let origin be settingsorigin.

  5. Let navigable be document’s node navigable.

  6. While navigable has a non-null parent:

    1. Set navigable to navigable’s parent.

    2. If navigable’s active document's origin is not same origin with origin, return false.

  7. Return true.

2.1.2. Credential Type Registry

This registry maps credential types (i.e., [[type]] values) to various values associated with a given credential type. For example: the Options Member Identifier (formally, a dictionary member identifier) used in CredentialCreationOptions and CredentialRequestOptions (i.e., "options dictionaries") by their specifications.

Note: This registry is used by the relevant credential interface objects algorithm.

Credential Type
(in alphabetical order)
Options Member Identifier Appropriate Interface Object Get Permissions Policy Create Permissions Policy Specification Requestor Contact
digital-credential digital DigitalCredential digital-credentials-get null [DIGITAL-CREDENTIALS] WICG
federated federated FederatedCredential null null This specification: § 4 Federated Credentials W3C
identity identity IdentityCredential identity-credentials-get null [FEDCM] W3C
otp otp OTPCredential otp-credentials null [WEB-OTP] WICG
password password PasswordCredential null null This specification: § 3 Password Credentials W3C
public-key publicKey PublicKeyCredential publickey-credentials-get publickey-credentials-create [WEBAUTHN] W3C
2.1.2.1. Registration Entry Requirements and Update Process

An update to this registry is an addition, change or deletion of a credential type's registry entry. Any person can request an update to this registry by pull requests to the webappsec-credential-management repository. The Web Applications Security Working Group will place it on an upcoming meeting agenda and notify the requestor. Consideration and disposition of the request is by consensus of the W3C Web Applications Security Working Group. The Chair will then notify the requestor of the outcome and update the registry accordingly.

2.2. The Credential Interface

[Exposed=Window, SecureContext]
interface Credential {
  readonly attribute USVString id;
  readonly attribute DOMString type;
  static Promise<boolean> isConditionalMediationAvailable();
  static Promise<undefined> willRequestConditionalCreation();
};
id, of type USVString, readonly

The credential’s identifier. The requirements for the identifier are distinct for each type of credential. It might represent a username for username/password tuples, for example.

type, of type DOMString, readonly

This attribute’s getter returns the value of the object’s interface object's [[type]] slot, which specifies the credential type represented by this object.

isConditionalMediationAvailable()

Returns a Promise that resolves with true if and only if the user agent supports the conditional approach to mediation of credential requests for the credential type, false otherwise.

Credential's default implementation of isConditionalMediationAvailable():

  1. Return a promise resolved with with false.

The specification for any credential type supporting conditional mediation must explicitly override this function to resolve to true.

Note: If this function is not present, conditional mediation is not supported for the credential type.

willRequestConditionalCreation()

Returns a Promise that resolves after the user agent registers the relying party’s intention to create a credential using the conditional approach to mediation of credential creation for the credential type.

Credential's default implementation of willRequestConditionalCreation():

  1. Return a promise resolved with undefined.

Note: If this method is not present, conditional mediation for credential creation is not supported for the credential type.

[[type]]

The Credential interface object has an internal slot named [[type]], which unsurprisingly contains a string representing the credential type. The slot’s value is the empty string unless otherwise specified. See § 2.1.2 Credential Type Registry for a list of credential types.

Note: The [[type]] slot’s value will be the same for all credentials implementing a particular interface, which means that developers can rely on obj.type returning a string that unambiguously represents the specific kind of Credential they’re dealing with.

[[discovery]]

The Credential interface object has an internal slot named [[discovery]], representing the mechanism by which the user agent can collect credentials of a given type. Its value is either "credential store" or "remote". The former value means that all available credential information is stored in the user agent’s credential store, while the latter means that the user agent can discover credentials outside of those explicitly represented in the credential store via interaction with some external device or service.

Talk to Tobie/Dominic about the interface object bits, here and in § 2.5.1 Request a Credential, etc. I’m not sure I’ve gotten the terminology right. interface prototype object, maybe?

Some Credential objects are origin bound: these contain an internal slot named [[origin]], which stores the origin for which the Credential may be effective.

2.2.1. Credential Internal Methods

The Credential interface object features several internal methods facilitating retrieval and storage of Credential objects, with default "no-op" implementations as specified in this section, below.

Unless otherwise specified, each interface object created for interfaces which inherit from Credential MUST provide implementations for at least one of these internal methods, overriding Credential's default implementations, as appropriate for the credential type. E.g., § 3.2 The PasswordCredential Interface, § 4.1 The FederatedCredential Interface, and [WEBAUTHN].

2.2.1.1. [[CollectFromCredentialStore]] internal method
[[CollectFromCredentialStore]](origin, options, sameOriginWithAncestors) is called with an origin, a CredentialRequestOptions, and a boolean which is true if and only if the caller’s environment settings object is same-origin with its ancestors. The algorithm returns a set of Credential objects from the user agent’s credential store that match the options provided. If no matching Credential objects are available, the returned set will be empty.

Credential's default implementation of [[CollectFromCredentialStore]](origin, options, sameOriginWithAncestors):

  1. Return an empty set.

2.2.1.2. [[DiscoverFromExternalSource]] internal method
[[DiscoverFromExternalSource]](origin, options, sameOriginWithAncestors) is called in parallel with an origin, a CredentialRequestOptions object, and a boolean which is true if and only if the caller’s environment settings object is same-origin with its ancestors. It returns a Credential if one can be returned given the options provided, null if no credential is available, or throws an error if discovery fails (for example, incorrect options could produce a TypeError). If this kind of Credential is only effective for a single use or a limited time, this method is responsible for generating new credentials using a credential source.

Credential's default implementation of [[DiscoverFromExternalSource]](origin, options, sameOriginWithAncestors):

  1. Return null.

2.2.1.3. [[Store]] internal method
[[Store]](credential, sameOriginWithAncestors) is called in parallel with a Credential, and a boolean which is true if and only if the caller’s environment settings object is same-origin with its ancestors. The algorithm returns once Credential is persisted to the credential store.

Credential's default implementation of [[Store]](credential, sameOriginWithAncestors):

  1. Throw a NotSupportedError.

2.2.1.4. [[Create]] internal method
[[Create]](origin, options, sameOriginWithAncestors) is called in parallel with an origin, a CredentialCreationOptions, and a boolean which is true if and only if the caller’s environment settings object is same-origin with its ancestors. The algorithm either:

When creating a Credential, it will return an algorithm that takes a global object and returns an interface object inheriting from Credential. This algorithm MUST be invoked from a task.

Note: This algorithm’s steps are defined on a per-credential type basis.

Credential's default implementation of [[Create]](origin, options, sameOriginWithAncestors):

  1. Return null.

2.2.2. CredentialUserData Mixin

Some Credential objects contain data which aims to give users a human-readable disambiguation mechanism in the credential chooser by providing a friendly name and icon:

[SecureContext]
interface mixin CredentialUserData {
  readonly attribute USVString name;
  readonly attribute USVString iconURL;
};
name, of type USVString, readonly

A name associated with the credential, intended as a human-understandable public name for display in a credential chooser.

iconURL, of type USVString, readonly

A URL pointing to an image for the credential, intended for display in a credential chooser. This URL MUST be an potentially trustworthy URL.

2.3. navigator.credentials

Developers retrieve Credentials and interact with the user agent’s credential store via methods exposed on the CredentialsContainer interface, which hangs off the Navigator object as navigator.credentials.

partial interface Navigator {
  [SecureContext, SameObject] readonly attribute CredentialsContainer credentials;
};

The credentials attribute MUST return the CredentialsContainer associated with the active document's browsing context.

Note: As discussed in § 6.3 Insecure Sites, the credential management API is exposed only in Secure Contexts.

[Exposed=Window, SecureContext]
interface CredentialsContainer {
  Promise<Credential?> get(optional CredentialRequestOptions options = {});
  Promise<undefined> store(Credential credential);
  Promise<Credential?> create(optional CredentialCreationOptions options = {});
  Promise<undefined> preventSilentAccess();
};

dictionary CredentialData {
  required USVString id;
};
get(options)

When get() is called, the user agent MUST return the result of executing Request a Credential on options.

Arguments for the CredentialsContainer.get(options) method.
Parameter Type Nullable Optional Description
options CredentialRequestOptions The set of properties governing the scope of the request.
store(credential)

When store() is called, the user agent MUST return the result of executing Store a Credential on credential.

Arguments for the CredentialsContainer.store(credential) method.
Parameter Type Nullable Optional Description
credential Credential The credential to be stored.
create(options)

When create() is called, the user agent MUST return the result of executing Create a Credential on options.

Arguments for the CredentialsContainer.create(options) method.
Parameter Type Nullable Optional Description
options CredentialCreationOptions The options used to create a Credential.
preventSilentAccess()

When preventSilentAccess() is called, the user agent MUST return the result of executing Prevent Silent Access on the current settings object.

Note: The intent here is a signal from the origin that the user has signed out. That is, after a click on a "Sign out" button, the site updates the user’s session info, and calls navigator.credentials.preventSilentAccess(). This sets the prevent silent access flag, meaning that credentials will not be automagically handed back to the page next time the user visits.

Note: This function was previously called requireUserMediation() which should be considered deprecated.

When a Navigator object (navigator) is created, the user agent MUST create a new CredentialsContainer object, using navigator’s relevant Realm, and associate it with navigator.

2.3.1. The CredentialRequestOptions Dictionary

In order to retrieve a Credential via get(), the caller specifies a few parameters in a CredentialRequestOptions object.

Note: The CredentialRequestOptions dictionary is an extension point. If and when new types of credentials are introduced that require options, their dictionary types will be added to the dictionary so they can be passed into the request. See § 8.2 Extension Points.

dictionary CredentialRequestOptions {
  CredentialMediationRequirement mediation = "optional";
  AbortSignal signal;
};
mediation, of type CredentialMediationRequirement, defaulting to "optional"

This property specifies the mediation requirements for a given credential request. The meaning of each enum value is described below in CredentialMediationRequirement. Processing details are defined in § 2.5.1 Request a Credential.

signal, of type AbortSignal

This property lets the developer abort an ongoing get() operation. An aborted operation may complete normally (generally if the abort was received after the operation finished) or reject with an abort reason.

Earlier versions of this specification defined a boolean unmediated member. Setting that to true had the effect of setting mediation to "silent", and setting it to false had the effect of setting mediation to "optional".

unmediated should be considered deprecated; new code should instead rely on mediation.

The relevant credential interface objects for a given CredentialCreationOptions or CredentialRequestOptions (options) is a set of interface objects, collected as follows:

Note: This algorithm uses the Credential Type Registry.

  1. Let settings be the current settings object.

  2. Let relevant interface objects be an empty set.

  3. For each optionKeyoptionValue of options:

    1. Let credentialInterfaceObject be the Appropriate Interface Object (on settingsglobal object) whose Options Member Identifier is optionKey.

    2. Assert: credentialInterfaceObject’s [[type]] slot equals the Credential Type whose Options Member Identifier is optionKey.

    3. Append credentialInterfaceObject to relevant interface objects.

  4. Return relevant interface objects.

A given CredentialRequestOptions (options) is matchable a priori if the following steps return true:
  1. For each interface in optionsrelevant credential interface objects:

    1. If interface’s [[discovery]] slot’s value is not "credential store", return false.

  2. Return true.

Note: When executing get(options), we only return credentials without user mediation if the provided CredentialRequestOptions is matchable a priori. If any credential types are requested that could require discovery from some external service (OAuth tokens, security key authenticators, etc.), then user mediation will be required in order to guide the discovery process (by choosing a federated identity provider, BTLE device, etc).

2.3.2. Mediation Requirements

When making a request via get(options) or create(options), developers can set a case-by-case requirement for user mediation by choosing the appropriate CredentialMediationRequirement enum value.

Note: The § 5 User Mediation section gives more detail on the concept in general, and its implications on how the user agent deals with individual requests for a given origin).

enum CredentialMediationRequirement {
  "silent",
  "optional",
  "conditional",
  "required"
};
silent

User mediation is suppressed for the given operation. If the operation can be performed without user involvement, wonderful. If user involvement is necessary, then the operation will return null rather than involving the user.

Note: The intended usage is to support "Keep me signed-into this site" scenarios, where a developer may wish to silently obtain credentials if a user should be automatically signed in, but to delay bothering the user with a sign-in prompt until they actively choose to sign-in.

optional

If credentials can be handed over for a given operation without user mediation, they will be. If user mediation is required, then the user agent will involve the user in the decision.

Note: This is the default behavior for get(), and is intended to serve a case where a developer has reasonable confidence that a user expects to start a sign-in operation. If a user has just clicked "sign-in" for example, then they won’t be surprised or confused to see a credential chooser if necessary.

conditional

For get(), discovered credentials are presented to the user in a non-modal dialog along with an indication of the origin which is requesting credentials. If the user makes a gesture outside of the dialog, the dialog closes without resolving or rejecting the Promise returned by the get() method and without causing a user-visible error condition. If the user makes a gesture that selects a credential, that credential is returned to the caller. The prevent silent access flag is treated as being true regardless of its actual value: the conditional behavior always involves user mediation of some sort if applicable credentials are discovered.

If no credentials are discovered, the user agent MAY prompt the user to take action in a way that depends on the type of credential (e.g. to insert a device containing credentials). Either way, the get() method MUST NOT resolve immediately with null to avoid revealing the lack of applicable credentials to the website.

Websites can only pass conditional into the get() method if all of the credential interfaces it refers to have overridden isConditionalMediationAvailable() to return a Promise that resolves with true.

For create(), if a user has previously consented to credential creation and the user agent knows it recently mediated an authentication, then the create() call may resolve without additional prominent modal interaction. If the user agent did not recently mediate an authentication or does not have consent for credential creation, then the call must throw a "NotAllowedError" DOMException.

required

The user agent will not hand over credentials without user mediation, even if the prevent silent access flag is unset for an origin.

Note: This requirement is intended to support reauthentication or user-switching scenarios. Further, the requirement is tied to a specific operation, and does not affect the prevent silent access flag for the origin. To set that flag, developers should call preventSilentAccess().

2.3.2.1. Examples
MegaCorp, Inc. wishes to seamlessly sign in users when possible. They can do so by calling get() for all non-signed in users at some convinient point while a landing page is loading, passing in a mediation member set to "silent". This ensures that users who have opted-into dropping the requirements for user mediation (as described in § 5.2 Requiring User Mediation) are signed in, and users who haven’t opted-into such behavior won’t be bothered with a confusing credential chooser popping up without context:
window.addEventListener('load', async () => {
  const credentials = await navigator.credentials.get({
    ...,
    mediation: 'silent'
  });
  if (credentials) {
    // Hooray! Let’s sign the user in using these credentials!
  }
});
When a user clicks "Sign In", MegaCorp, Inc. wishes to give them the smoothest possible experience. If they have opted-into signing in without user mediation, and the user agent can unambigiously choose a credential, great! If not, a credential chooser will be presented.
document.querySelector('#sign-in').addEventListener('click', async () => {
  const credentials = await navigator.credentials.get({
    ...,
    mediation: 'optional'
  });
  if (credentials) {
    // Hooray! Let’s sign the user in using these credentials!
  }
});

Note: MegaCorp, Inc. could also have left off the mediation member entirely, as "optional" is its default.

MegaCorp, Inc. wishes to protect a sensitive operation by requiring a user to reauthenticate before taking action. Even if a user has opted-into signing in without user mediation, MegaCorp, Inc. can ensure that the user agent requires mediation by calling get() with a mediation member set to "required":

Note: Depending on the security model of the browser or the credential type, this may require the user to authenticate themselves in some way, perhaps by entering a master password, scanning a fingerprint, etc. before a credential is handed to the website.

document.querySelector('#important-form').addEventListener('submit', async () => {
  const credentials = await navigator.credentials.get({
    ...,
    mediation: 'required'
  });
  if (credentials) {
    // Verify that |credentials| enables access, and cancel the submission
    // if it doesn’t.
  } else {
    e.preventDefault();
  }
});
MegaCorp, Inc. wishes to support signing into multiple user accounts at once. In order to ensure that the user gets a chance to select a different credential, MegaCorp, Inc. can call get() with a mediation member set to "required" in order to ensure that that credentials aren’t returned automatically in response to clicking on an "Add account" button:
document.querySelector('#switch-button').addEventListener('click', e => {
  var c = await navigator.credentials.get({
    ...,
    mediation: 'required'
  });
  if (c) {
    // Sign the user in using |c|.
  }
});

2.4. The CredentialCreationOptions Dictionary

In order to create a Credential via create(), the caller specifies a few parameters in a CredentialCreationOptions object.

Note: The CredentialCreationOptions dictionary is an extension point. If and when new types of credentials are introduced, they will add to the dictionary so they can be passed into the creation method. See § 8.2 Extension Points, and the extensions introduced in this document: § 3.2 The PasswordCredential Interface and § 4.1 The FederatedCredential Interface.

dictionary CredentialCreationOptions {
  CredentialMediationRequirement mediation = "optional";
  AbortSignal signal;
};
signal, of type AbortSignal

This property lets the developer abort an ongoing create() operation. An aborted operation may complete normally (generally if the abort was received after the operation finished) or reject with an abort reason.

2.5. Algorithms

2.5.1. Request a Credential

The Request a Credential algorithm accepts a CredentialRequestOptions (options), and returns a Promise that resolves with a Credential if one can be unambigiously obtained, or with null if not.

  1. Let settings be the current settings object.

  2. Assert: settings is a secure context.

  3. Let document be settings’s relevant global object's associated Document.

  4. If document is not fully active, then return a promise rejected with an "InvalidStateError" DOMException.

  5. If options.signal is aborted, then return a promise rejected with options.signal’s abort reason.

  6. Let interfaces be options’s relevant credential interface objects.

  7. If interfaces is empty, then returna promise rejected with a "NotSupportedError" DOMException.

  8. For each interface of interfaces:

    1. If options.mediation is conditional and interface does not support conditional user mediation, return a promise rejected with a "TypeError" DOMException.

    2. If settingsactive credential types contains interface’s [[type]], return a promise rejected with a "NotAllowedError" DOMException.

    3. Append interface’s [[type]] to settingsactive credential types.

  9. Let origin be settingsorigin.

  10. Let sameOriginWithAncestors be true if settings is same-origin with its ancestors, and false otherwise.

  11. For each interface in optionsrelevant credential interface objects:

    1. Let permission be the interface’s [[type]] Get Permissions Policy.

    2. If permission is null, continue.

    3. If document is not allowed to use permission, return a promise rejected with a "NotAllowedError" DOMException.

  12. Let p be a new promise.

  13. Run the following steps in parallel:

    1. Let credentials be the result of collecting Credentials from the credential store, given origin, options, and sameOriginWithAncestors.

    2. If credentials is an exception, reject p with credentials.

    3. If all of the following statements are true, resolve p with credentials[0] and skip the remaining steps:

      1. credentialssize is 1

      2. origin does not require user mediation

      3. options is matchable a priori.

      4. options.mediation is not "required".

      5. options.mediation is not "conditional".

      This might be the wrong model. It would be nice to support a site that wished to accept either username/passwords or webauthn-style credentials without forcing a chooser for those users who use the former, and who wish to remain signed in.

    4. If optionsmediation is "silent", resolve p with null, and skip the remaining steps.

    5. Let result be the result of asking the user to choose a Credential, given options and credentials.

    6. If result is an interface object:

      1. Set result to the result of executing result’s [[DiscoverFromExternalSource]](origin, options, sameOriginWithAncestors), given origin, options, and sameOriginWithAncestors.

        If that threw an exception:

        1. Let e be the thrown exception.

        2. Queue a task on global’s DOM manipulation task source to run the following substeps:

          1. Reject p with e.

        3. Terminate these substeps.

    7. Assert: result is null, or a Credential.

    8. If result is a Credential, resolve p with result.

    9. If result is null and options.mediation is not conditional, resolve p with result.

      Note: if options.mediation is conditional and a null credential is discovered, promise p is not resolved.

  14. React to p:

    1. For each interface in interfaces:

      1. Remove interface’s [[type]] from settingsactive credential types.

  15. Return p.

2.5.2. Collect Credentials from the credential store

Given an origin (origin), a CredentialRequestOptions (options), and a boolean which is true if and only if the calling context is same-origin with its ancestors (sameOriginWithAncestors), the user agent may collect Credentials from the credential store, returning a set of Credential objects stored by the user agent locally that match options’ filter. If no such Credential objects are known, the returned set will be empty:

  1. Let possible matches be an empty set.

  2. For each interface in optionsrelevant credential interface objects:

    1. Let r be the result of executing interface’s [[CollectFromCredentialStore]](origin, options, sameOriginWithAncestors) internal method on origin, options, and sameOriginWithAncestors. If that threw an exception, rethrow that exception.

    2. Assert: r is a list of interface objects.

    3. For each c in r:

      1. Append c to possible matches.

  3. Return possible matches.

2.5.3. Store a Credential

The Store a Credential algorithm accepts a Credential (credential), and returns a Promise which resolves once the object is persisted to the credential store.

  1. Let settings be the current settings object.

  2. Assert: settings is a secure context.

  3. If settings’s relevant global object's associated Document is not fully active, then return a promise rejected with an "InvalidStateError" DOMException.

  4. Let sameOriginWithAncestors be true if the current settings object is same-origin with its ancestors, and false otherwise.

  5. Let p be a new promise.

  6. If settingsactive credential types contains credential’s [[type]], return a promise rejected with a "NotAllowedError" DOMException.

  7. Append credential’s [[type]] to settingsactive credential types.

  8. Run the following steps in parallel:

    1. Execute credential’s interface object's [[Store]](credential, sameOriginWithAncestors) internal method on credential and sameOriginWithAncestors.

      If that threw an exception:

      1. Let e be the thrown exception.

      2. Queue a task on global’s DOM manipulation task source to run the following substeps:

        1. Reject p with e.

      Otherwise, resolve p with undefined.

  9. React to p:

    1. Remove credential’s [[type]] from settingsactive credential types.

  10. Return p.

2.5.4. Create a Credential

The Create a Credential algorithm accepts a CredentialCreationOptions (options), and returns a Promise which resolves with a Credential if one can be created using the options provided, or null if no Credential can be created. In exceptional circumstances, the Promise may reject with an appropriate exception:

  1. Let settings be the current settings object.

  2. Assert: settings is a secure context.

  3. Let global be settingsglobal object.

  4. Let document be the relevant global object's associated Document.

  5. If document is not fully active, then return a promise rejected with an "InvalidStateError" DOMException.

  6. Let sameOriginWithAncestors be true if the current settings object is same-origin with its ancestors, and false otherwise.

  7. Let interfaces be the set of optionsrelevant credential interface objects.

  8. Return a promise rejected with NotSupportedError if any of the following statements are true:

    1. global does not have an associated Document.

    2. interfacessize is greater than 1.

      Note: It may be reasonable at some point in the future to loosen this restriction, and allow the user agent to help the user choose among one of many potential credential types in order to support a "sign-up" use case. For the moment, though, we’re punting on that by restricting the dictionary to a single entry.

  9. For each interface in interfaces:

    1. Let permission be the interface’s [[type]] Create Permissions Policy.

    2. If permission is null, continue.

    3. If document is not allowed to use permission, return a promise rejected with a "NotAllowedError" DOMException.

  10. If options.signal is aborted, then return a promise rejected with options.signal’s abort reason.

  11. Let type be interfaces[0]'s [[type]].

  12. If settingsactive credential types contains type, return a promise rejected with a "NotAllowedError" DOMException.

  13. Append type to settingsactive credential types.

  14. Let origin be settings’s origin.

  15. Let p be a new promise.

  16. Run the following steps in parallel:

    1. Let r be the result of executing interfaces[0]'s [[Create]](origin, options, sameOriginWithAncestors) internal method on origin, options, and sameOriginWithAncestors.

      If that threw an exception:

      1. Let e be the thrown exception.

      2. Queue a task on global’s DOM manipulation task source to run the following substeps:

        1. Reject p with e.

      3. Terminate these substeps.

    2. If r is a Credential or null, resolve p with r, and terminate these substeps.

    3. Assert: r is an algorithm (as defined in § 2.2.1.4 [[Create]] internal method).

    4. Queue a task on global’s DOM manipulation task source to run the following substeps:

      1. Resolve p with the result of promise-calling r given global.

  17. React to p:

    1. Remove type from settingsactive credential types.

  18. Return p.

2.5.5. Prevent Silent Access

The Prevent Silent Access algorithm accepts an environment settings object (settings), and returns a Promise which resolves once the prevent silent access flag is persisted to the credential store.

  1. Let origin be settingsorigin.

  2. If settings’s relevant global object's associated Document is not fully active, then return a promise rejected with an "InvalidStateError" DOMException.

  3. Let p be a new promise.

  4. Run the following seps in parallel:

    1. Set origin’s prevent silent access flag in the credential store.

    2. Resolve p with undefined.

  5. Return p.

3. Password Credentials

For good or for ill, many websites rely on username/password pairs as an authentication mechanism. The PasswordCredential interface is a credential meant to enable this use case, storing both a username and password, as well as metadata that can help a user choose the right account from within a credential chooser.

3.1. Examples

3.1.1. Password-based Sign-in

MegaCorp, Inc. supports passwords, and can use navigator.credentials.get() to obtain username/password pairs from a user’s credential store:
navigator.credentials
  .get({ 'password': true })
  .then(credential => {
    if (!credential) {
      // The user either doesn’t have credentials for this site, or
      // refused to share them. Insert some code here to fall back to
      // a basic login form.
      return;
    }
    if (credential.type == 'password') {
      var form = new FormData();
      form.append('username_field', credential.id);
      form.append('password_field', credential.password);
      var opt = {
        method: 'POST',
        body: form,
        credentials: 'include'  // Send cookies.
      };
      fetch('https://example.com/loginEndpoint', opt)
        .then(function (response) {
          if (/* |response| indicates a successful login */) {
            // Record that the credential was effective. See note below.
            navigator.credentials.store(credential);
            // Notify the user that sign-in succeeded! Do amazing, signed-in things!
            // Maybe navigate to a landing page via location.href =
            // '/signed-in-experience'?
          } else {
            // Insert some code here to fall back to a basic login form.
          }
        });
    }
  });

Alternatively, the website could just copy the credential data into a form and call submit() on the form:

navigator.credentials
  .get({ 'password': true })
  .then(credential => {
    if (!credential) {
      return; // as above...
    }
    if (credential.type === 'password') {
      document.querySelector('input[name=username_field]').value =
        credential.id;
      document.querySelector('input[name=password_field]').value =
        credential.password;
      document.getElementById('myform').submit();
    }
  });

Note that the former method is much preferred, as it contains an explicit call to store() and saves the credentials. The form based mechanism relies on form submission, which navigates the browsing context, making it difficult to ensure that store() is called after successful sign-in.

Note: The credential chooser presented by the user agent could allow the user to choose credentials that aren’t actually stored for the current origin. For instance, it might offer up credentials from https://m.example.com when signing into https://www.example.com (as described in § 6.1 Cross-domain credential access), or it might allow a user to create a new credential on the fly. Developers can deal gracefully with this uncertainty by calling store() every time credentials are successfully used, even right after credentials have been retrieved from get(): if the credentials aren’t yet stored for the origin, the user will be given the opportunity to do so. If they are stored, the user won’t be prompted.

3.1.2. Post-sign-in Confirmation

To ensure that users are offered to store new credentials after a successful sign-in, they can to be passed to store().

If a user is signed in by submitting the credentials to a sign-in endpoint via fetch(), we can check the response to determine whether the user was signed in successfully, and notify the user agent accordingly. Given a sign-in form like the following:
<form action="https://example.com/login" method="POST" id="theForm">
  <label for="username">Username</label>
  <input type="text" id="username" name="username" autocomplete="username">
  <label for="password">Password</label>
  <input type="password" id="password" name="password" autocomplete="current-password">
  <input type="submit">
</form>

Then the developer can handle the form submission with something like the following handler:

document.querySelector('#theForm').addEventListener('submit', e => {
    if (window.PasswordCredential) {
      e.preventDefault();

      // Construct a new PasswordCredential from the HTMLFormElement
      // that fired the "submit" event: this will suck up the values of the fields
      // labeled with "username" and "current-password" autocomplete
      // attributes:
      var c = new PasswordCredential(e.target);

      // Fetch the form’s action URL, passing that new credential object in
      // as a FormData object. If the response indicates success, tell the user agent
      // so it can ask the user to store the password for future use:
      var opt = {
        method: 'POST',
        body: new FormData(e.target),
        credentials: 'include'  // Send cookies.
      };
      fetch(e.target.action, opt).then(r => {
        if (/* |r| is a "successful" Response */)
          navigator.credentials.store(c);
      });
    }
});

3.1.3. Change Password

This same storage mechanism can be reused for "password change" with no modifications: if the user changes their credentials, the website can notify the user agent that they’ve successfully signed in with new credentials. The user agent can then update the credentials it stores:

MegaCorp Inc. allows users to change their passwords by POSTing data to a backend server asynchronously. After doing so successfully, they can update the user’s credentials by calling store() with the new information.

Given a password change form like the following:

<form action="https://example.com/changePassword" method="POST" id="theForm">
  <input type="hidden" name="username" autocomplete="username" value="user">
  <label for="password">New Password</label>
  <input type="password" id="password" name="password" autocomplete="new-password">
  <input type="submit">
</form>

The developer can handle the form submission with something like the following:

document.querySelector('#theForm').addEventListener('submit', e => {
  if (window.PasswordCredential) {
    e.preventDefault();

    // Construct a new PasswordCredential from the HTMLFormElement
    // that fired the "submit" event: this will suck up the values of the fields
    // labeled with "username" and "new-password" autocomplete
    // attributes:
    var c = new PasswordCredential(e.target);

    // Fetch the form’s action URL, passing that new credential object in
    // as a FormData object. If the response indicates success, tell the user agent
    // so it can ask the user to store the password for future use:
    var opt = {
      method: 'POST',
      body: new FormData(e.target),
      credentials: 'include'  // Send cookies.
    };
    fetch(e.target.action, opt).then(r => {
      if (/* |r| is a "successful" Response */)
        navigator.credentials.store(c);
    });
  }
});

3.2. The PasswordCredential Interface

[Exposed=Window,
 SecureContext]
interface PasswordCredential : Credential {
  constructor(HTMLFormElement form);
  constructor(PasswordCredentialData data);
  readonly attribute USVString password;
};
PasswordCredential includes CredentialUserData;

partial dictionary CredentialRequestOptions {
  boolean password = false;
};
password, of type USVString, readonly

This attribute represents the password of the credential.

[[type]]

The PasswordCredential interface object has an internal slot named [[type]] whose value is "password".

[[discovery]]

The PasswordCredential interface object has an internal slot named [[discovery]] whose value is "credential store".

PasswordCredential(form)

This constructor accepts an HTMLFormElement (form), and runs the following steps:

  1. Let origin be the current settings object's origin.

  2. Let r be the result of executing Create a PasswordCredential from an HTMLFormElement given form and origin.

  3. If r is an exception, throw r.

    Otherwise, return r.

PasswordCredential(data)

This constructor accepts a PasswordCredentialData (data), and runs the following steps:

  1. Let r be the result of executing Create a PasswordCredential from PasswordCredentialData on data.

  2. If r is an exception, throw r.

    Otherwise, return r.

PasswordCredential objects can be created via navigator.credentials.create() either explicitly by passing in a PasswordCredentialData dictionary, or based on the contents of an HTMLFormElement's submittable elements.

dictionary PasswordCredentialData : CredentialData {
  USVString name;
  USVString iconURL;
  required USVString origin;
  required USVString password;
};

typedef (PasswordCredentialData or HTMLFormElement) PasswordCredentialInit;

partial dictionary CredentialCreationOptions {
  PasswordCredentialInit password;
};

PasswordCredential objects are origin bound.

PasswordCredential's interface object inherits Credential's implementation of [[DiscoverFromExternalSource]](origin, options, sameOriginWithAncestors), and defines its own implementation of [[CollectFromCredentialStore]](origin, options, sameOriginWithAncestors), [[Create]](origin, options, sameOriginWithAncestors), and [[Store]](credential, sameOriginWithAncestors).

3.3. Algorithms

3.3.1. PasswordCredential’s [[CollectFromCredentialStore]](origin, options, sameOriginWithAncestors)

[[CollectFromCredentialStore]](origin, options, sameOriginWithAncestors) is called with an origin (origin), a CredentialRequestOptions (options), and a boolean which is true if and only if the calling context is same-origin with its ancestors (sameOriginWithAncestors). The algorithm returns a set of Credential objects from the credential store. If no matching Credential objects are available, the returned set will be empty.

The algorithm will throw a NotAllowedError if sameOriginWithAncestors is not true.

  1. Assert: options["password"] exists.

  2. If sameOriginWithAncestors is false, throw a "NotAllowedError" DOMException.

    Note: This restriction aims to address the concern raised in § 6.4 Origin Confusion.

  3. Return the empty set if options["password"] is not true.

  4. Return the result of retrieving credentials from the credential store that match the following filter:

    1. The credential is a PasswordCredential

    2. The credential’s [[origin]] is the same origin as origin.

3.3.2. PasswordCredential’s [[Create]](origin, options, sameOriginWithAncestors)

[[Create]](origin, options, sameOriginWithAncestors) is called with an origin (origin), a CredentialCreationOptions (options), and a boolean which is true if and only if the calling context is same-origin with its ancestors (sameOriginWithAncestors). The algorithm returns a PasswordCredential if one can be created, null otherwise. The CredentialCreationOptions dictionary must have a password member which holds either an HTMLFormElement or a PasswordCredentialData. If that member’s value cannot be used to create a PasswordCredential, this algorithm will throw a TypeError exception.

  1. Assert: options["password"] exists, and sameOriginWithAncestors is unused.

  2. If options["password"] is an HTMLFormElement, return the result of executing Create a PasswordCredential from an HTMLFormElement given options["password"] and origin. Rethrow any exceptions.

  3. If options["password"] is a PasswordCredentialData, return the result of executing Create a PasswordCredential from PasswordCredentialData given options["password"]. Rethrow any exceptions.

  4. Throw a TypeError exception.

3.3.3. PasswordCredential’s [[Store]](credential, sameOriginWithAncestors)

[[Store]](credential, sameOriginWithAncestors) is called with a PasswordCredential (credential), and a boolean which is true if and only if the calling context is same-origin with its ancestors (sameOriginWithAncestors). The algorithm returns undefined once credential is persisted to the credential store.

The algorithm will return a NotAllowedError if sameOriginWithAncestors is not true.

  1. Throw a "NotAllowedError" DOMException without altering the user agent’s credential store if sameOriginWithAncestors is false.

    Note: This restriction aims to address the concern raised in § 6.4 Origin Confusion.

  2. If the user agent’s credential store contains a PasswordCredential (stored) whose id attribute is credential’s id and whose [[origin]] slot is the same origin as credential’s [[origin]], then:

    1. If the user grants permission to update credentials (as discussed when defining user mediation), then:

      1. Set stored’s password to credential’s password.

      2. Set stored’s name to credential’s name.

      3. Set stored’s iconURL to credential’s iconURL.

    Otherwise, if the user grants permission to store credentials (as discussed when defining user mediation, then:

    1. Store a PasswordCredential in the credential store with the following properties:

      id

      credential’s id

      name,

      credential’s name

      iconURL

      credential’s iconURL

      [[origin]]

      credential’s [[origin]]

      password

      credential’s password

3.3.4. Create a PasswordCredential from an HTMLFormElement

To Create a PasswordCredential from an HTMLFormElement, given an HTMLFormElement (form) and an origin (origin), run these steps.

Note: § 3.1.2 Post-sign-in Confirmation and § 3.1.3 Change Password provide examples of the intended usage.

  1. Let data be a new PasswordCredentialData dictionary.

  2. Set data’s origin member’s value to origin’s value.

  3. Let formData be the result of executing the FormData constructor on form.

  4. Let elements be a list of all the submittable elements whose form owner is form, in tree order.

  5. Let newPasswordObserved be false.

  6. For each field in elements, run the following steps:

    1. If field does not have an autocomplete attribute, then skip to the next field.

    2. Let name be the value of field’s name attribute.

    3. If formData’s has() method returns false when executed on name, then skip to the next field.

    4. If field’s autocomplete attribute’s value contains one or more autofill detail tokens (tokens), then:

      1. For each token in tokens:

        1. If token is an ASCII case-insensitive match for one of the following strings, run the associated steps:

          "new-password"

          Set data’s password member’s value to the result of executing formData’s get() method on name, and newPasswordObserved to true.

          "current-password"

          If newPasswordObserved is false, set data’s password member’s value to the result of executing formData’s