--- title: APi de Autenticação da Web slug: Web/API/API_Autenticacao_Web tags: - API - API de Autenticação da Web - Landing - Referencia translation_of: Web/API/Web_Authentication_API ---
{{draft}}{{SeeCompatTable}}{{securecontext_header}}{{DefaultAPISidebar("Web Authentication API")}}

A "API de Autenticação da Web" é uma extensão de Credential Management API que permite uma autenticação forte com a criptografia de chave pública, permitindo a autenticação sem palavra-passe e/ou autenticação de segundo fator segura sem textos de SMS.

Conceitos e utilização da autenticação da Web

The Web Authtentication API (also referred to as WebAuthn) uses asymmetric (public-key) cryptography instead of passwords or SMS texts for registering, authenticating, and second-factor authentication with websites. This resolves significant security problems related to phishing, data breaches, and attacks against SMS texts or other second-factor authentication methods while at the same time significantly increasing ease of use (since users don't have to manage dozens of increasingly complicated passwords).

Many websites already have pages that allow users to register new accounts or sign in to an existing account, and WebAuthn acts as a replacement or suppliment to those on those existing webpages. Similar to the other forms of the Credential Management API, the Web Authentication API has two basic methods that correspond to register and login:

Por favor, note: both create() and get() require a Secure Context (e.g. - the server is connected by https or is the localhost), and will not be available for use if the browser is not operating in a secure context.

In their most basic forms, both create() and get() receive a very large random number called a challenge from the server and they return the challenge signed by the private key back to the server. This proves to the server that a user is in possession of the private key required for authentication without revealing any secrets over the network.

In order to understand how the create() and get() methods fit into the bigger picture, it is important to understand that they sit between two components that are outside the browser:

  1. Servidor - the WebAuthn API is intended to register new credentials on a server (also referred to as a service or a relying party) and later use those same credentials on that same server to authenticate a user.
  2. Autenticador - the credentials are created and stored in a device called an authenticator. This is a new concept in authentication: when authenticating using passwords, the password is stored in a user's brain and no other device is needed; when authenticating using WebAuthn, the password is replaced with a key pair that is stored in an authenticator. The authenticator may be embedded into an operating system, such as Windows Hello, or may be a physical token, such as a USB or Bluetooth Security Key.

Registo

A typical registration process has six steps, as illustrated in Figure 1 and described further below. This is a simplification of the data required for the registration process that is only intended to provide an overview. The full set of required fields, optional fields, and their meanings for creating a registration request can be found in the {{domxref("PublicKeyCredentialCreationOptions")}} dictionary. Likewise, the full set of response fields can be found in the {{domxref("PublicKeyCredential")}} interface (where {{domxref("PublicKeyCredential.response")}} is the {{domxref("AuthenticatorAttestationResponse")}} interface). Note most JavaScript programmers that are creating an application will only really care about steps 1 and 5 where the create() function is called and subsequently returns; however, steps 2, 3, and 4 are essential to understanding the processing that takes place in the browser and authenticator and what the resulting data means.

WebAuthn registration component and dataflow diagram

Figura 1 - a diagram showing the sequence of actions for a WebAuthn registration and the essential data associated with each action.

Os passos de registo são:

  1. Registo de Pedidos da Aplicação - The application makes the initial registration request. The protocol and format of this request is outside of the scope of WebAuthn.
  2. Servidor Envia Desafio, Informação do Utilziador, e Envio de Informação de Confiança - The server sends a challenge, user information, and relying party information to the JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of WebAuthn. Typically, server communications would be REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the create() call, typically with little or no modification and returns a Promise that will resolve to a {{domxref("PublicKeyCredential")}} containing an {{domxref("AuthenticatorAttestationResponse")}}. Note that it is absolutely critical that the challenge be a large buffer of random information (e.g. - more than 100 bytes) and it MUST be generated on the server in order to ensure the security of the registration process.
  3. Navegador Chama o authenticatorMakeCredential() no Autenticador - Internally, the browser will validate the parameters and fill in any defaults, which become the {{domxref("AuthenticatorResponse.clientDataJSON")}}. One of the most important parameters is the origin, which recorded as part of the clientData so that the origin can be verified by the server later. The parameters to the create() call are passed to the authenticator, along with a SHA-256 hash of the clientDataJSON (only a hash is sent because the link to the authenticator may be a low-bandwidth NFC or Bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with).
  4. Autenticador Cria Novo Par de Chave e Certificação - Before doing anything, the authenticator will typically ask for some form of user verficiation. This could be entering a PIN, using a fingerprint, doing an iris scan, etc. to prove that the user is present and consenting of the registration. After the user verification, the authenticator will create a new asymmetric key pair and safely store the private key for future reference. The public key will become part of the attestation, which the authtenticator will sign over with a private key that was burned into the authenticator during its manufacturing process and that has a certificate chain that can be validated back to a root of trust.
  5. Autenticador Devolve os Dados para o Navegador - The new public key, a globally unique credential id, and other attestation data are returned to the browser where they become the attestationObject.
  6. Navegador Cria os Dados Finais, a Aplicação envia a resposta para o Servidor - The create() Promise resolves to an {{domxref("PublicKeyCredential")}}, which has a {{domxref("PublicKeyCredential.rawId")}} that is the globally unique credential id along with a response that is the {{domxref("AuthenticatorAttestationResponse")}} containing the {{domxref("AuthenticatorResponse.clientDataJSON")}} and {{domxref("AuthenticatorAttestationResponse.attestationObject")}}. The {{domxref("PublicKeyCredential")}} is sent back to the server using any desired formatting and protocol (note that the ArrayBuffer properties need to be be base64 encoded or similar).
  7. Servidor Valida e Finaliza o Registo - Finally, the server is required to perform a series of checks to ensure that the registration was complete and not tampered with. These include:
    1. Verifying that the challenge is the same as the challenge that was sent
    2. Ensuring that the origin was the origin expected
    3. Validating that the signature over the clientDataHash and the attestation using the certificate chain for that specific model of authenticator
    A complete list of validation steps can be found in the WebAuthn specification. Assuming that the checks pan out, the server will store the new public key associated with the user's account for future use -- that is, whenever the user desires to use the public key for authentication.

Autenticação

After a user has registered with WebAuthn, they can subsequently authenticate (a.k.a. - login or sign-in) with the service. The authentication flow looks similar to the registration flow, and the illustration of actions in Figure 2 may be recognizable as being similar to the illustration of registration actions in Figure 1. The primary differences between registration and authentication are that: 1) authentication doesn't require user or relying party information; and 2) authentication creates an assertion using the previously generated key pair for the service rather than creating an attestation with the key pair that was burned into the authenticator during manufacturing. Again, the discription of authentication below is a broad overview rather than getting into all the options and features of WebAuthn. The specific options for authenticating can be found in the {{domxref("PublicKeyCredentialRequestOptions")}} dictionary, and the resulting data can be found in the {{domxref("PublicKeyCredential")}} interface (where {{domxref("PublicKeyCredential.response")}} is the {{domxref("AuthenticatorAssertionResponse")}} interface) .

WebAuthn authentication component and dataflow diagram

Figure 2 - similar to Figure 1, a diagram showing the sequence of actions for a WebAuthn authentication and the essential data associated with each action.

  1. Auyenticação dos Pedidos da Aplicação - The application makes the initial authentication request. The protocol and format of this request is outside of the scope of WebAuthn.
  2. Servidor Envia Desafio - The server sends a challenge JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of WebAuthn. Typically, server communications would be REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the get() call, typically with little or no modification. Note that it is absolutely critical that the challenge be a large buffer of random information (e.g. - more than 100 bytes) and it MUST be generated on the server in order to ensure the security of the authentication process.
  3. Navegador Chama o authenticatorGetCredential()  no Autenticador - Internally, the browser will validate the parameters and fill in any defaults, which become the {{domxref("AuthenticatorResponse.clientDataJSON")}}. One of the most important parameters is the origin, which recorded as part of the clientData so that the origin can be verified by the server later. The parameters to the create() call are passed to the authenticator, along with a SHA-256 hash of the clientDataJSON (only a hash is sent because the link to the authenticator may be a low-bandwidth NFC or Bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with).
  4. Autenticador Cria uma Certificação  - The authenticator finds a credential for this service that matches the Relying Party ID and prompts a user to consent to the authentication. Assuming both of those steps are successful, the authenticator will create a new assertion by signing over the clientDataHash and authenticatorData with the private key generated for this account during the registration call.
  5. Autenticador Devolve os Dados para o Navegador -  The authenticator returns the authenticatorData and assertion signature back to the browser.
  6. Navegador Cria os Dados Finais, a Aplicação envia a resposta para o Servidor - The browser resolves the Promise to a {{domxref("PublicKeyCredential")}} with a {{domxref("PublicKeyCredential.response")}} that contains the {{domxref("AuthenticatorAssertionResponse")}}. It is up to the JavaScript application to transmit this data back to the server using any protocol and format of its choice.
  7. Servidor Valida e Finaliza a Autenticação - Upon receiving the result of the authentication request, the server performs validation of the response such as:
    1. Using the public key that was stored during the registration request to validate the signature by the authenticator.
    2. Ensuring that the challenge that was signed by the authenticator matches the challenge that was generated by the server.
    3. Checking that the Relying Party ID is the one expected for this service.
    A full list of the steps for validating an assertion can be found in the WebAuthn specification. Assuming the validation is successful, the server will note that the user is now authenticated. This is outside the scope of the WebAuthn specification, but one option would be to drop a new cookie for the user session.

Interfaces

{{domxref("CredentialsContainer")}}
WebAuthn extends the Credential Management API's create() and get() methods to take a new option: publicKey. When the publicKey option is passed to create() and / or get(), the Credential Management API will create a new public key pair or get an authentication for a key pair, respectively.
{{domxref("PublicKeyCredential")}}
A credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password.
{{domxref("AuthenticatorResponse")}}
Part of the PublicKeyCredential, the AuthenticatorResponse includes information from the browser (such as the challenge and origin); as well as information from the authenticator such as an AuthenticatorAttestationResponse (for new credentials) or an AuthenticatorAssertionResponse (when authenticating with existing credentials).
{{domxref("AuthenticatorAttestationResponse")}}
When a PublicKeyCredential has been created with the create() call, it will include an AuthenticatorAttestationResponse. This is the authenticator's way of providing a cryptographic root of trust for the new key pair that has been generated.
{{domxref("AuthenticatorAssertionResponse")}}
When a PublicKeyCredential is the result of a get() call, it will include an AuthenticatorAssertionResponse. This is the authenticator's way of proving to a service that it has the key pair and that the authentication request is valid and approved.

Opções

{{domxref("PublicKeyCredentialCreationOptions")}}
The options for creating a credential via navigator.credentials.create()
{{domxref("PublicKeyCredentialRequestOptions")}}
The options for using a credential via navigator.credentials.get()

Exemplos

Especificações

Especificação Estado Comentário
{{SpecName('WebAuthn')}} {{Spec2('WebAuthn')}} Definção inicial.

Compatibilidade do Navegador

{{Compat("api.PublicKeyCredential")}}

Consulte também: