Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

CredentialsContainer: get() method

BaselineWidely available *

Secure context: This feature is available only insecure contexts (HTTPS), in some or allsupporting browsers.

Theget() method of theCredentialsContainer interface returns aPromise that fulfills with a singlecredential, which can then be used to authenticate a user to a website.

The method accepts a single optionaloptions argument, which may include:

  • Amediation 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.
  • Asignal property enabling the operation to be cancelled using anAbortController.
  • One or more properties —password,federated,identity,otp,publicKey — which indicate thetypes 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 ornull. If multiple credentials are available and user mediation is allowed, then the browser will ask the user to select a single credential.

Syntax

js
get()get(options)

Parameters

optionsOptional

An object that contains options for the request. It can contain the following properties:

mediationOptional

A string indicating whether the user will be required to login for every visit to a client app. The value can be one of the following:

"conditional"

Discovered credentials are presented to the user in a non-modal dialog box along with an indication of the origin requesting credentials. In practice, this means autofilling available credentials; seeSign in with a passkey through form autofill for more details of how this is used;PublicKeyCredential.isConditionalMediationAvailable() also provides some useful information.

"optional"

If credentials can be handed over for a given operation without user mediation, they will be, enabling automatic reauthentication without user mediation. If user mediation is required, then the user agent will ask the user to authenticate. This value is intended for situations where you have reasonable confidence that a user won't be surprised or confused at seeing a login dialog box — for example on a site that doesn't automatically log users in, when a user has just clicked a "Login/Signup" button.

"required"

The user will always be asked to authenticate. This value is intended for situations where you want to force user authentication — for example if you want a user to reauthenticate when a sensitive operation is being performed (like confirming a credit card payment), or when switching users.

"silent"

The user will not be asked to authenticate. The user agent will automatically reauthenticate the user and log them in if possible. If consent is required, the promise will fulfill withnull. 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 afederated authentication (FedCM API) request, amediation value ofoptional orsilent may result in attemptedauto-reauthentication. Whether this occurred is communicated to the identity provider (IdP) via theis_auto_selected parameter sent to the IdP'sid_assertion_endpoint during validation and the relying party (RP) via theIdentityCredential.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).

signalOptional

AnAbortSignal object instance that allows an ongoingget() operation to be aborted. An aborted operation may complete normally (generally if the abort was received after the operation finished) or reject with anAbortErrorDOMException.

passwordOptional

This option asks the browser to retrieve a storedpassword as aPasswordCredential object. It is a boolean value.

identityOptional

This option asks the browser to retrieve afederated identity credential as anIdentityCredential object, using theFederated Credential Management API.

This option's value is anIdentityCredentialRequestOptions object containing details of the specific identity providers that the website wants to use.

federatedOptional

This option asks the browser to retrieve afederated identity credential as aFederatedCredential object. This interface is now superseded, and developers should prefer to use theidentity option, if it is available.

This option's value is an object with the following properties:

protocols

An array of strings representing the protocols of the requested credentials' federated identity providers (for example,"openidconnect").

providers

An array of strings representing the credentials' federated identity providers (for example"https://www.facebook.com" or"https://accounts.google.com").

otpOptional

This option asks the browser to retrieve aone-time password (OTP) as anOTPCredential object.

This option's value is an array of strings which may only contain the string value"sms".

publicKeyOptional

This option asks the browser to retrieve anassertion signed using the Web Authentication API as aPublicKeyCredential.

This option's value is aPublicKeyCredentialRequestOptions object.

Return value

APromise that resolves with one of the following subclasses ofCredential:

Ifconditional mediation was specified in theget() 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 the user then makes a gesture outside of the browser UI dialog, it closes without resolving or rejecting the promise and without causing a user-visible error condition.
  • If the user selects a credential, the relevantPublicKeyCredential is returned to the caller.

If a single credential cannot be unambiguously obtained, the promise resolves withnull.

Exceptions

AbortErrorDOMException

The request was aborted by a call to theabort() method of theAbortController associated with this method'ssignal option.

IdentityCredentialErrorDOMException

When requesting anIdentityCredential, the request to theID assertion endpoint is unable to validate the authentication, and rejects with an error response containing information about the reason.

NetworkErrorDOMException

When requesting anIdentityCredential, theidentity provider (IdP) did not respond within 60 seconds, the provided credentials were not valid/found, or the browser's login status for the IdP is set to"logged-out" (seeUpdate 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.

NotAllowedErrorDOMException

Thrown in one of the following situations:

SecurityErrorDOMException

The calling domain is not a valid domain.

Examples

Retrieving a federated identity credential

Relying parties can callget() with theidentity 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:

js
async function signIn() {  const identityCredential = await navigator.credentials.get({    identity: {      providers: [        {          configURL: "https://accounts.idp.example/config.json",          clientId: "********",          nonce: "******",        },      ],    },  });}

Check outFederated Credential Management (FedCM) API for more details on how this works. This call will start off the sign-in flow described inFedCM sign-in flow.

A similar call including thecontext andloginHint extensions would look like so:

js
async function signIn() {  const identityCredential = await navigator.credentials.get({    identity: {      context: "signup",      providers: [        {          configURL: "https://accounts.idp.example/config.json",          clientId: "********",          nonce: "******",          loginHint: "user1@example.com",        },      ],    },  });}

If the IdP is unable to validate a request to theID assertion endpoint it will reject the promise returned fromCredentialsContainer.get():

js
async function signIn() {  try {    const identityCredential = await navigator.credentials.get({      identity: {        providers: [          {            configURL: "https://accounts.idp.example/config.json",            clientId: "********",            nonce: "******",          },        ],      },    });  } 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);  }}

Retrieving a public key credential

The following snippet shows a typicalget() call with the WebAuthnpublicKey option:

js
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 successfulget() call returns a promise that resolves with aPublicKeyCredential object instance, representing a public key credential previously created via a WebAuthncreate() that has now been used to authenticate a user. ItsPublicKeyCredential.response property contains anAuthenticatorAssertionResponse object providing access to several useful pieces of information including the authenticator data, signature, and user handle.

js
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 thesignature to provide proof that authenticator possesses the genuine private key used to create the credential, and theuserHandle to link the user with the credential, sign in attempt, and other data.

SeeAuthenticating a user for more information about how the overall flow works.

Retrieving a one-time password

The code below triggers the browser's permission flow when an SMS message arrives. If permission is granted, then the promise resolves with anOTPCredential object. The containedcode value is then set as the value of an<input> form element, which is then submitted.

js
navigator.credentials  .get({    otp: { transport: ["sms"] },    signal: ac.signal,  })  .then((otp) => {    input.value = otp.code;    if (form) form.submit();  })  .catch((err) => {    console.error(err);  });

Specifications

Specification
Credential Management Level 1
# dom-credentialscontainer-get

Browser compatibility

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp