1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
|
---
title: Web Authentication API
slug: Web/API/Web_Authentication_API
translation_of: Web/API/Web_Authentication_API
---
<div>{{securecontext_header}}{{DefaultAPISidebar("Web Authentication API")}}</div>
<p class="summary">API Web Authentication - расширение <a href="/en-US/docs/Web/API/Credential_Management_API">Credential Management API</a>, добавляющее аутентификацию с использованием криптографии с открытым ключом, вход без пароля и/или надёжный второй фактор, не требующий SMS.</p>
<h2 id="Принципы_и_использование_веб-аутентификации">Принципы и использование веб-аутентификации</h2>
<p>API Web Authentication (также называемое WebAuthn) использует {{interwiki("wikipedia", "Public-key_cryptography", "ассиметричную криптографию (систему с открытым ключом)")}} вместо паролей или SMS-сообщений для регистрации, входа и {{interwiki("wikipedia", "Multi-factor_authentication", "двухфакторной аутентификации")}} на веб-сайтах. Это устраняет многие значительные проблемы безопасности, такие как {{interwiki("wikipedia", "Phishing", "фишинг")}}, {{interwiki("wikipedia", "Data_breach", "утечки данных")}} и атаки на SMS или иные методы двухфакторной аутентификации, при этом сильно упрощая использование, т.к. пользователям не нужно запоминать десятки сложных паролей.</p>
<p>На многих сайтах уже есть страницы для регистрации и входа в существующие учётные записи, и Web Authentication API может быть как заменой, так и дополнением для них. Как и остальные виды <a href="/en-US/docs/Web/API/Credential_Management_API">Credential Management API</a>, Web Authentication API содержит два базовых метода: для регистрации и для входа:</p>
<ul>
<li>{{domxref("CredentialsContainer.create()", "navigator.credentials.create()")}} - при использовании с опцией <code>publicKey</code> создаёт новый набор учётных данных для регистрации нового аккаунта или добавления пары ключей к уже существующему.</li>
<li>{{domxref("CredentialsContainer.get()", "navigator.credentials.get()")}} - при использовании с опцией <code>publicKey</code> использует существующий набор учётных данных для аутентификации в сервисе в качестве основного способа входа или второго фактора.</li>
</ul>
<p><strong>Обратите внимание</strong>, и <code>create()</code>, и <code>get()</code> работают только в <a href="/en-US/docs/Web/Security/Secure_Contexts">Secure Context</a> (например, когда подключение к серверу происходит через https или сервер работает на localhost).</p>
<p>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.</p>
<p>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:</p>
<ol>
<li><strong>Server</strong> - the Web Authentication API is intended to register new credentials on a server (also referred to as a service or a <a href="https://en.wikipedia.org/wiki/Relying_party">relying party</a>) and later use those same credentials on that same server to authenticate a user.</li>
<li><strong>Authenticator</strong> - 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 web authentication, 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.</li>
</ol>
<h3 id="Регистрация">Регистрация</h3>
<p>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.</p>
<p><img alt="Web Authentication API registration component and dataflow diagram" src="https://mdn.mozillademos.org/files/16189/WebAuthn_Registration_r4.png" style="height: 547px; width: 1134px;"></p>
<p><em>Figure 1 - a diagram showing the sequence of actions for a web authentication registration and the essential data associated with each action.</em></p>
<p>The registration steps are:</p>
<ol start="0">
<li><strong>Приложение запрашивает регистрацию</strong> - The application makes the initial registration request. The protocol and format of this request is outside of the scope of the Web Authentication API.</li>
<li><strong>Server Sends Challenge, User Info, and Relying Party Info</strong> - 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 the Web Authentication API. Typically, server communications would be <a href="/en-US/docs/Glossary/REST">REST</a> over https (probably using <a href="/en-US/docs/User:maybe/webidl_mdn/XMLHttpRequest_API">XMLHttpRequest</a> or <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a>), but they could also be <a href="/en-US/docs/Glossary/SOAP">SOAP</a>, <a href="https://tools.ietf.org/html/rfc2549">RFC 2549</a> or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the <a href="/en-US/docs/Web/API/CredentialsContainer/create">create()</a> call, typically with little or no modification and returns a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> that will resolve to a {{domxref("PublicKeyCredential")}} containing an {{domxref("AuthenticatorAttestationResponse")}}. <strong>Note that it is absolutely critical that the challenge be a buffer of random information (at least 16 bytes) and it MUST be generated on the server in order to ensure the security of the registration process.</strong></li>
<li><strong>Браузер вызывает authenticatorMakeCredential() для аутентификатора</strong> - 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 is 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).</li>
<li><strong>Аутентификатор создаёт новую пару ключей и Attestation</strong> - Before doing anything, the authenticator will typically ask for some form of user verification. This could be entering a PIN, using a fingerprint, doing an iris scan, etc. to prove that the user is present and consenting to 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 authenticator 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.</li>
<li><strong>Аутентификатор передаёт информацию в браузер</strong> - The new public key, a globally unique credential id, and other attestation data are returned to the browser where they become the attestationObject.</li>
<li><strong>Браузер создаёт итоговый набор данных, приложение отвечает серверу</strong> - 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).</li>
<li><strong>Сервер проверят и завершает регистрацию</strong> - Finally, the server is required to perform a series of checks to ensure that the registration was complete and not tampered with. These include:
<ol>
<li>Verifying that the challenge is the same as the challenge that was sent</li>
<li>Ensuring that the origin was the origin expected</li>
<li>Validating that the signature over the clientDataHash and the attestation using the certificate chain for that specific model of the authenticator</li>
</ol>
A complete list of validation steps <a href="https://w3c.github.io/webauthn/#registering-a-new-credential">can be found in the Web Authentication API specification</a>. 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.</li>
</ol>
<h3 id="Аутентификация">Аутентификация</h3>
<p>After a user has registered with web authentication, 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 description of authentication below is a broad overview rather than getting into all the options and features of the Web Authentication API. 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) .</p>
<p><img alt="WebAuthn authentication component and dataflow diagram" src="https://mdn.mozillademos.org/files/15802/MDN%20Webauthn%20Authentication%20(r1).png" style="height: 527px; width: 1067px;"></p>
<p><em>Figure 2 - similar to Figure 1, a diagram showing the sequence of actions for a web authentication and the essential data associated with each action.</em></p>
<ol start="0">
<li><strong>Приложение запрашивает аутентификацию</strong> - The application makes the initial authentication request. The protocol and format of this request is outside of the scope of the Web Authentication API.</li>
<li><strong>Server Sends Challenge</strong> - The server sends a challenge to the JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of the Web Authentication API. Typically, server communications would be <a href="/en-US/docs/Glossary/REST">REST</a> over https (probably using <a href="/en-US/docs/User:maybe/webidl_mdn/XMLHttpRequest_API">XMLHttpRequest</a> or <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a>), but they could also be <a href="/en-US/docs/Glossary/SOAP">SOAP</a>, <a href="https://tools.ietf.org/html/rfc2549">RFC 2549</a> or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the <a href="/en-US/docs/Web/API/CredentialsContainer/get">get()</a> call, typically with little or no modification. <strong>Note that it is absolutely critical that the challenge be a buffer of random information (at least 16 bytes) and it MUST be generated on the server in order to ensure the security of the authentication process.</strong></li>
<li><strong>Браузер вызывает authenticatorGetCredential() для аутентификатора</strong> - 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 get() 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).</li>
<li><strong>Аутентификатор создаёт подпись</strong> - 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.</li>
<li><strong>Аутентификатор передаёт информацию в браузер</strong> - The authenticator returns the authenticatorData and assertion signature back to the browser.</li>
<li><strong>Браузер создаёт итоговый набор данных, приложение отвечает серверу</strong> - The browser resolves the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> 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.</li>
<li><strong>Сервер проверят и завершает аутентификацию</strong> - Upon receiving the result of the authentication request, the server performs validation of the response such as:
<ol>
<li>Using the public key that was stored during the registration request to validate the signature by the authenticator.</li>
<li>Ensuring that the challenge that was signed by the authenticator matches the challenge that was generated by the server.</li>
<li>Checking that the Relying Party ID is the one expected for this service.</li>
</ol>
A full list of the <a href="https://w3c.github.io/webauthn/#verifying-assertion">steps for validating an assertion can be found in the Web Authentication API specification</a>. Assuming the validation is successful, the server will note that the user is now authenticated. This is outside the scope of the Web Authentication API specification, but one option would be to drop a new cookie for the user session.</li>
</ol>
<h2 id="Интерфейсы">Интерфейсы</h2>
<dl>
<dt>{{domxref("Credential")}} {{experimental_inline}}</dt>
<dd>Provides information about an entity as a prerequisite to a trust decision.</dd>
<dt>{{domxref("CredentialsContainer")}}</dt>
<dd>Exposes methods to request credentials and notify the user agent when events such as successful sign in or sign out happen. This interface is accessible from {{domxref('Navigator.credentials')}}. The Web Authentication specification adds a <code>publicKey</code> member to the {{domxref('CredentialsContainer.create','create()')}} and {{domxref('CredentialsContainer.get','get()')}} methods to either create a new public key pair or get an authentication for a key pair, repsectively.</dd>
<dt>{{domxref("PublicKeyCredential")}}</dt>
<dd>Provides information about a public key / private key pair, which is a credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password.</dd>
<dt>{{domxref("AuthenticatorResponse")}}</dt>
<dd>The base interface for {{domxref("AuthenticatorAttestationResponse")}} and {{domxref("AuthenticatorAssertionResponse")}}, which provide a cryptographic root of trust for a key pair. Returned by {{domxref('CredentialsContainer.create()')}} and {{domxref('CredentialsContainer.get()')}}, respectively, the child interfaces include information from the browser such as the challenge origin. Either may be returned from {{domxref("PublicKeyCredential.response")}}.</dd>
<dt>{{domxref("AuthenticatorAttestationResponse")}}</dt>
<dd>Returned by {{domxref('CredentialsContainer.create()')}} when a {{domxref('PublicKeyCredential')}} is passed, and provides a cryptographic root of trust for the new key pair that has been generated.</dd>
<dt>{{domxref("AuthenticatorAssertionResponse")}}</dt>
<dd>Returned by {{domxref('CredentialsContainer.get()')}} when a {{domxref('PublicKeyCredential')}} is passed, and provides proof to a service that it has a key pair and that the authentication request is valid and approved.</dd>
</dl>
<h2 id="Опции">Опции</h2>
<dl>
<dt>{{domxref("PublicKeyCredentialCreationOptions")}}</dt>
<dd>Опции для {{domxref('CredentialsContainer.create()')}}.</dd>
<dt>{{domxref("PublicKeyCredentialRequestOptions")}}</dt>
<dd>Опции для {{domxref('CredentialsContainer.get()')}}.</dd>
</dl>
<h2 id="Примеры">Примеры</h2>
<div class="blockIndicator warning">
<p> В целях безопасности вызовы Web Authentication API ({{domxref('CredentialsContainer.create','create()')}} и {{domxref('CredentialsContainer.get','get()')}}) отменяются, если браузер теряет фокус до завершения вызова.</p>
</div>
<pre class="brush: js notranslate">// sample arguments for registration
var createCredentialDefaultArgs = {
publicKey: {
// Relying Party (a.k.a. - Service):
rp: {
name: "Acme"
},
// User:
user: {
id: new Uint8Array(16),
name: "john.p.smith@example.com",
displayName: "John P. Smith"
},
pubKeyCredParams: [{
type: "public-key",
alg: -7
}],
attestation: "direct",
timeout: 60000,
challenge: new Uint8Array([ // must be a cryptographically random number sent from a server
0x8C, 0x0A, 0x26, 0xFF, 0x22, 0x91, 0xC1, 0xE9, 0xB9, 0x4E, 0x2E, 0x17, 0x1A, 0x98, 0x6A, 0x73,
0x71, 0x9D, 0x43, 0x48, 0xD5, 0xA7, 0x6A, 0x15, 0x7E, 0x38, 0x94, 0x52, 0x77, 0x97, 0x0F, 0xEF
]).buffer
}
};
// sample arguments for login
var getCredentialDefaultArgs = {
publicKey: {
timeout: 60000,
// allowCredentials: [newCredential] // see below
challenge: new Uint8Array([ // must be a cryptographically random number sent from a server
0x79, 0x50, 0x68, 0x71, 0xDA, 0xEE, 0xEE, 0xB9, 0x94, 0xC3, 0xC2, 0x15, 0x67, 0x65, 0x26, 0x22,
0xE3, 0xF3, 0xAB, 0x3B, 0x78, 0x2E, 0xD5, 0x6F, 0x81, 0x26, 0xE2, 0xA6, 0x01, 0x7D, 0x74, 0x50
]).buffer
},
};
// register / create a new credential
navigator.credentials.create(createCredentialDefaultArgs)
.then((cred) => {
console.log("NEW CREDENTIAL", cred);
// normally the credential IDs available for an account would come from a server
// but we can just copy them from above...
var idList = [{
id: cred.rawId,
transports: ["usb", "nfc", "ble"],
type: "public-key"
}];
getCredentialDefaultArgs.publicKey.allowCredentials = idList;
return navigator.credentials.get(getCredentialDefaultArgs);
})
.then((assertion) => {
console.log("ASSERTION", assertion);
})
.catch((err) => {
console.log("ERROR", err);
});
</pre>
<ul>
<li><span class="external">Сайт </span><a class="external" href="https://webauthn.bin.coffee/">Mozilla Demo</a> и его <a href="https://github.com/jcjones/webauthn.bin.coffee">source code</a>.</li>
<li><span class="external">Сайт </span><a class="external" href="http://webauthndemo.appspot.com/">Google Demo</a> и его <a href="https://github.com/google/webauthndemo">source code</a>.</li>
<li><a href="https://webauthn.org">webauthn.org</a>: <a href="https://github.com/apowers313/webauthn-simple-app">client source code</a> и <a href="https://github.com/apowers313/fido2-lib">server source code</a></li>
</ul>
<h2 id="Спецификации">Спецификации</h2>
{{Specifications}}
<h2 id="Совместимость">Совместимость</h2>
<h3 id="Credential">Credential</h3>
<p>{{Compat("api.Credential")}}</p>
<h3 id="CredentialsContainer">CredentialsContainer</h3>
<p>{{Compat("api.CredentialsContainer")}}</p>
<h3 id="PublicKeyCredential">PublicKeyCredential</h3>
<p>{{Compat("api.PublicKeyCredential")}}</p>
<h3 id="AuthenticatorResponse">AuthenticatorResponse</h3>
<p>{{Compat("api.AuthenticatorResponse")}}</p>
<h3 id="AuthenticatorAttestationResponse">AuthenticatorAttestationResponse</h3>
<p>{{Compat("api.AuthenticatorAttestationResponse")}}</p>
<h3 id="AuthenticatorAssertionResponse">AuthenticatorAssertionResponse</h3>
<p>{{Compat("api.AuthenticatorAssertionResponse")}}</p>
<h3 id="PublicKeyCredentialCreationOptions">PublicKeyCredentialCreationOptions</h3>
<p>{{Compat("api.PublicKeyCredentialCreationOptions")}}</p>
<h3 id="PublicKeyCredentialRequestOptions">PublicKeyCredentialRequestOptions</h3>
<p>{{Compat("api.PublicKeyCredentialRequestOptions")}}</p>
<h2 id="See_also">See also</h2>
<ul>
<li><span class="st"><a href="https://secure.wphackedhelp.com/blog/wordpress-two-factor-authentication/">WordPress Two-Factor Authentication</a>, ( 2FA) is an additional layer of security you can add to your <em>WordPress</em> login page.</span></li>
</ul>
|