files/en-us/web/api/credentialscontainer/get/index.md
{{APIRef("Credential Management API")}}{{SecureContext_Header}}
The get() method of the {{domxref("CredentialsContainer")}} interface returns a {{jsxref("Promise")}} that fulfills with a single {{glossary("credential")}}, which can then be used to authenticate a user to a website.
The method accepts a single optional options argument, which may include:
mediation property indicating how and whether the user should be asked to participate in the operation.
This controls, for example, whether the site can silently sign a user in using a stored credential.signal property enabling the operation to be cancelled using an {{domxref("AbortController")}}.password, federated, identity, otp, publicKey — which indicate the types of credential being requested. If set, the values of these properties include any parameters that the browser needs in order to find an appropriate credential of the requested type.The API always fulfills with a single credential or null. If multiple credentials are available and user mediation is allowed, then the browser will ask the user to select a single credential.
get()
get(options)
options {{optional_inline}}
mediation {{optional_inline}}
: A string indicating how the user is involved in retrieving the credential. The value can be one of the following:
"conditional"
"optional"
"required"
"silent"
null. This value is intended for situations where you would want to automatically sign a user in upon visiting a web app if possible, but if not, you don't want to present them with a confusing login dialog box. Instead, you'd want to wait for them to explicitly click a "Login/Signup" button.The default value is "optional".
[!NOTE] In the case of a federated authentication (FedCM API) request, a
mediationvalue ofoptionalorsilentmay result in attempted auto-reauthentication. Whether this occurred is communicated to the identity provider (IdP) via theis_auto_selectedparameter sent to the IdP'sid_assertion_endpointduring validation and the relying party (RP) via the {{domxref("IdentityCredential.isAutoSelected")}} property. This is useful for performance evaluation, security requirements (the IdP may wish to reject automatic reauthentication requests and always require user mediation), and general UX (an IdP or RP may wish to present different UX for auto and non-auto login experiences).
signal {{optional_inline}}
get() operation to be aborted. An aborted operation may complete normally (generally if the abort was received after the operation finished) or reject with the signal's reason (which is an AbortError {{domxref("DOMException")}} by default, or a custom value if one was provided when calling {{domxref("AbortController.abort", "abort()")}}).password {{optional_inline}}
identity {{optional_inline}}
: This option asks the browser to retrieve a federated identity credential as an {{domxref("IdentityCredential")}} object, using the Federated Credential Management API.
This option's value is an {{domxref("IdentityCredentialRequestOptions")}} object containing details of the specific identity providers that the website wants to use.
federated {{optional_inline}}
: This option asks the browser to retrieve a federated identity credential as a {{domxref("FederatedCredential")}} object. This interface is now superseded, and developers should prefer to use the identity option, if it is available.
This option's value is an object with the following properties:
protocols
"openidconnect").providers
"https://www.facebook.com" or "https://accounts.google.com").otp {{optional_inline}}
: This option asks the browser to retrieve a one-time password (OTP) as an {{domxref("OTPCredential")}} object.
This option's value is an array of strings which may only contain the string value "sms".
publicKey {{optional_inline}}
: This option asks the browser to retrieve an assertion signed using the Web Authentication API as a {{domxref("PublicKeyCredential")}}.
This option's value is a {{domxref("PublicKeyCredentialRequestOptions")}} object.
A {{jsxref("Promise")}} that resolves with one of the following subclasses of {{domxref("Credential")}}:
If conditional mediation was specified in the get() call, the browser UI dialog is shown and the promise remains pending until the user picks an account to sign-in with from available autofill suggestions:
If a single credential cannot be unambiguously obtained, the promise resolves with null.
AbortError {{domxref("DOMException")}}
signal option.
Note that if the caller of abort() provided a reason argument, then get() will be rejected with the value of reason, instead of an AbortController exception.TimeoutError {{domxref("DOMException")}}
{{domxref("IdentityCredentialError")}}
NetworkError {{domxref("DOMException")}}
"logged-out" (see Update login status using the Login Status API for more information about FedCM login status). In the latter case, there may be some delay in the rejection to avoid leaking the IdP login status to the RP.NotAllowedError {{domxref("DOMException")}}
The user canceled the request.
Use of this API was blocked by one of the following permissions policies:
The calling origin is an opaque origin.
SecurityError {{domxref("DOMException")}}
Relying parties can call get() with the identity option to make a request for users to sign in to the relying party via an identity provider (IdP), using identity federation. A typical request would look like this:
async function signIn() {
const identityCredential = await navigator.credentials.get({
identity: {
providers: [
{
configURL: "https://accounts.idp.example/config.json",
clientId: "********",
params: {
/* IdP-specific parameters */
},
},
],
},
});
}
Check out Federated Credential Management (FedCM) API for more details on how this works. This call will start off the sign-in flow described in FedCM sign-in flow.
A similar call including the context and loginHint extensions would look like so:
async function signIn() {
const identityCredential = await navigator.credentials.get({
identity: {
context: "signup",
providers: [
{
configURL: "https://accounts.idp.example/config.json",
clientId: "********",
params: {
/* IdP-specific parameters */
},
loginHint: "[email protected]",
},
],
},
});
}
If the IdP is unable to validate a request to the ID assertion endpoint it will reject the promise returned from CredentialsContainer.get():
async function signIn() {
try {
const identityCredential = await navigator.credentials.get({
identity: {
providers: [
{
configURL: "https://accounts.idp.example/config.json",
clientId: "********",
params: {
/* IdP-specific parameters */
},
},
],
},
});
} catch (e) {
// Handle the error in some way, for example provide information
// to help the user succeed in a future sign-in attempt
console.error(e);
}
}
The following snippet shows a typical get() call with the WebAuthn publicKey option:
const publicKey = {
challenge: new Uint8Array([139, 66, 181, 87, 7, 203 /* ,… */]),
rpId: "acme.com",
allowCredentials: [
{
type: "public-key",
id: new Uint8Array([64, 66, 25, 78, 168, 226, 174 /* ,… */]),
},
],
userVerification: "required",
};
navigator.credentials.get({ publicKey });
A successful get() call returns a promise that resolves with a {{domxref("PublicKeyCredential")}} object instance, representing a public key credential previously created via a WebAuthn {{domxref("CredentialsContainer.create()", "create()")}} that has now been used to authenticate a user. Its {{domxref("PublicKeyCredential.response")}} property contains an {{domxref("AuthenticatorAssertionResponse")}} object providing access to several useful pieces of information including the authenticator data, signature, and user handle.
navigator.credentials.get({ publicKey }).then((publicKeyCredential) => {
const response = publicKeyCredential.response;
// Access authenticator data ArrayBuffer
const authenticatorData = response.authenticatorData;
// Access client JSON
const clientJSON = response.clientDataJSON;
// Access signature ArrayBuffer
const signature = response.signature;
// Access userHandle ArrayBuffer
const userHandle = response.userHandle;
});
Some of this data will need to be stored on the server — for example the signature to provide proof that authenticator possesses the genuine private key used to create the credential, and the userHandle to link the user with the credential, sign in attempt, and other data.
See Authenticating a user for more information about how the overall flow works.
The code below triggers the browser's permission flow when an SMS message arrives. If permission is granted, then the promise resolves with an OTPCredential object. The contained code value is then set as the value of an {{htmlelement("input")}} form element, which is then submitted.
navigator.credentials
.get({
otp: { transport: ["sms"] },
signal: ac.signal,
})
.then((otp) => {
input.value = otp.code;
if (form) form.submit();
})
.catch((err) => {
console.error(err);
});
In this example, we use {{domxref("AbortSignal.timeout_static", "AbortSignal.timeout()")}} to automatically abort the request if it takes longer than 10 seconds.
async function authenticateUser() {
const publicKey = {
challenge: new Uint8Array([139, 66, 181, 87, 7, 203 /* ,… */]),
rpId: "acme.com",
allowCredentials: [
{
type: "public-key",
id: new Uint8Array([64, 66, 25, 78, 168, 226, 174 /* ,… */]),
},
],
userVerification: "required",
};
try {
const credential = await navigator.credentials.get({
publicKey,
signal: AbortSignal.timeout(10000), // Abort after 10 seconds
});
console.log("Authentication successful:", credential);
} catch (err) {
if (err.name === "TimeoutError") {
console.error("The authentication request timed out.");
} else if (err.name === "AbortError") {
console.log("The request was cancelled by the user.");
} else {
console.error("An unexpected error occurred:", err);
}
}
}
{{Specifications}}
{{Compat}}