CredentialsContainer: create() method
Baseline
Widely available
*
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2019.
* Some parts of this feature may have varying levels of support.
Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
The create() method of the CredentialsContainer interface creates a new credential, which can then be stored and later retrieved using the navigator.credentials.get() method. The retrieved credential can then be used by a website to authenticate a user.
This method supports three different types of credential:
- A password credential, which enables a user to sign in using a password.
- A federated credential, which enables a user to sign in using a federated identity provider. Note that the Federated Credential Management API (FedCM) supersedes the federated credential type.
- A public key credential, which enables a user to sign in with an authenticator such as a biometric reader built into the platform or a removable hardware token. Passkeys are a type of public key credential.
Syntax
create()
create(options)
Parameters
optionsOptional-
An object that contains options for the requested new
Credentialsobject. It can contain the following properties:mediationOptional-
A string indicating how the user is involved in creating the credential.
This option only has an effect for public key credentials, and the only value that has an effect is
"conditional". This value means that if certain conditions are met, then the browser will attempt to create the new credential without requiring any user interaction. If the conditions are not met, creation will fail. See Conditional create for more details. signalOptional-
An
AbortSignalobject instance that allows an ongoingcreate()operation to be aborted. An aborted operation may complete normally (generally if the abort was received after the operation finished) or reject with anAbortErrorDOMException.
Each of the following properties represents a credential type being created. One and only one of them must be specified:
federatedOptional-
A
FederatedCredentialInitobject containing requirements for creating a federated identify provider credential. passwordOptional-
A
PasswordCredentialInitobject containing requirements for creating a password credential. publicKeyOptional-
A
PublicKeyCredentialCreationOptionsobject containing requirements for creating a public key credential. Causes thecreate()call to request that the user agent creates new credentials via an authenticator — either for registering a new account or for associating a new asymmetric key pair with an existing account.Note: Usage of
create()with thepublicKeyparameter may be blocked by apublickey-credentials-createPermissions Policy set on your server.
Return value
A Promise that resolves with one of the following:
- A
FederatedCredential, if the credential type wasfederated. - A
PasswordCredential, if the credential type waspassword. - A
PublicKeyCredential, if the credential type waspublicKey.
If no credential object can be created, the promise resolves with null.
Exceptions
TypeError-
In the case of a
PasswordCredentialcreation request,id,origin, orpasswordwere not provided (empty). NotAllowedErrorDOMException-
Possible causes include:
- Usage is blocked by a
publickey-credentials-createPermissions Policy. - The function is called cross-origin but the iframe's
allowattribute does not set an appropriatepublickey-credentials-createpolicy. - The function is called cross-origin and the
<iframe>does not have transient activation. - The function tries to create a discoverable credential (
residentKeyis set torequiredin thecreate()call'sPublicKeyCredentialCreationOptionsoption), but the user does not have an authenticator that supports discoverable credentials. - The
mediationoption is set to"conditional", but the conditions were not met. See Conditional create for more details.
- Usage is blocked by a
AbortErrorDOMException-
The operation was aborted.
Examples
>Creating a password credential
This example creates a password credential from a PasswordCredentialInit object.
const credInit = {
id: "serpent1234", // "username" in a typical username/password pair
name: "Serpentina", // display name for credential
origin: "https://example.org",
password: "the last visible dog",
};
const makeCredential = document.querySelector("#make-credential");
makeCredential.addEventListener("click", async () => {
const cred = await navigator.credentials.create({
password: credInit,
});
console.log(cred.name);
// Serpentina
console.log(cred.id);
// serpent1234
console.log(cred.password);
// the last visible dog
});
Creating a federated credential
This example creates a federated credential from a FederatedCredentialInit object.
const credInit = {
id: "1234",
name: "Serpentina",
origin: "https://example.org",
protocol: "openidconnect",
provider: "https://provider.example.org",
};
const makeCredential = document.querySelector("#make-credential");
makeCredential.addEventListener("click", async () => {
const cred = await navigator.credentials.create({
federated: credInit,
});
console.log(cred.name);
console.log(cred.provider);
});
Creating a public key credential
This example creates a public key credential from a PublicKeyCredentialCreationOptions object.
const publicKey = {
challenge: challengeFromServer,
rp: { id: "acme.com", name: "ACME Corporation" },
user: {
id: new Uint8Array([79, 252, 83, 72, 214, 7, 89, 26]),
name: "jamiedoe",
displayName: "Jamie Doe",
},
pubKeyCredParams: [{ type: "public-key", alg: -7 }],
};
const publicKeyCredential = await navigator.credentials.create({ publicKey });
The create() call, if successful, returns a promise that resolves with a PublicKeyCredential object instance, representing a public key credential that can later be used to authenticate a user via a WebAuthn get() call. Its PublicKeyCredential.response property contains an AuthenticatorAttestationResponse object providing access to several useful pieces of information including the authenticator data, public key, transport mechanisms, and more.
navigator.credentials.create({ publicKey }).then((publicKeyCredential) => {
const response = publicKeyCredential.response;
// Access attestationObject ArrayBuffer
const attestationObj = response.attestationObject;
// Access client JSON
const clientJSON = response.clientDataJSON;
// Return authenticator data ArrayBuffer
const authenticatorData = response.getAuthenticatorData();
// Return public key ArrayBuffer
const pk = response.getPublicKey();
// Return public key algorithm identifier
const pkAlgo = response.getPublicKeyAlgorithm();
// Return permissible transports array
const transports = response.getTransports();
});
Some of this data will need to be stored on the server for future authentication operations against this credential — for example the public key, the algorithm used, and the permissible transports.
Note: See Creating a key pair and registering a user for more information about how the overall flow works.
Creating a public key credential using conditional create
This example uses conditional create, which is specified by setting the mediation option to conditional. It attempts to create a new passkey without requiring any user interaction, when the conditions defined for conditional create are met.
async function conditionalCreate(account) {
try {
const capabilities = await PublicKeyCredential.getClientCapabilities();
// Only attempt conditional create if it is supported,
// and if the user doesn't already have a passkey
if (capabilities.conditionalCreate && !account.hasPasskey) {
// Abort any existing WebAuthn calls
webAuthnController.abort();
// Get creation options, including the challenge value from the server
const pkOptions = await getNewPasskeyOptions();
const credential = await navigator.credentials.create({
publicKey: pkOptions,
mediation: "conditional",
});
// Conditional create succeeded: send the new credential to the server
// for validation and storage
await processNewPasskey(credential);
}
} catch (e) {
// Ignore errors from conditional create
}
}
Note that this example:
- Only attempts conditional create if the user does not already have a passkey
- Aborts any outstanding attempts to get or create a public key credential before attempting conditional create.
- Catches and ignores any errors that are thrown if, for example, the conditions were not met.
Specifications
| Specification |
|---|
| Credential Management Level 1> # dom-credentialscontainer-create> |