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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
|
/* eslint-disable @typescript-eslint/no-var-requires */
/**
* An example Express server showing off a simple integration of @simplewebauthn/server.
*
* The webpages served from ./public use @simplewebauthn/browser.
*/
const https = require('https');
const fs = require('fs');
const express = require('express');
const {
// Registration ("Attestation")
generateAttestationOptions,
verifyAttestationResponse,
// Login ("Assertion")
generateAssertionOptions,
verifyAssertionResponse,
} = require('@simplewebauthn/server');
const app = express();
const host = '0.0.0.0';
const port = 443;
app.use(express.static('./public/'));
app.use(express.json());
/**
* If the words "metadata statements" mean anything to you, you'll want to check out this file. It
* contains an example of a more complex deployment of SimpleWebAuthn with support enabled for the
* FIDO Metadata Service. This enables greater control over the types of authenticators that can
* interact with the Rely Party (a.k.a. "RP", a.k.a. "this server").
*/
// const { fidoRouteSuffix, fidoConformanceRouter } = require('./fido-conformance');
// app.use(fidoRouteSuffix, fidoConformanceRouter);
/**
* RP ID represents the "scope" of websites on which a authenticator should be usable. The Origin
* represents the expected URL from which an attestation or assertion occurs.
*/
const rpID = 'localhost';
const origin = `https://${rpID}`;
/**
* 2FA and Passwordless WebAuthn flows expect you to be able to uniquely identify the user that
* performs an attestation or assertion. The user ID you specify here should be your internal,
* _unique_ ID for that user (uuid, etc...). Avoid using identifying information here, like email
* addresses, as it may be stored within the authenticator.
*
* Here, the example server assumes the following user has completed login:
*/
const loggedInUserId = 'internalUserId';
/**
* You'll need a database to store a few things:
*
* 1. Users
*
* You'll need to be able to associate attestation and assertions challenges, and authenticators to
* a specific user
*
* 2. Challenges
*
* The totally-random-unique-every-time values you pass into every execution of
* `generateAttestationOptions()` or `generateAssertionOptions()` MUST be stored until
* `verifyAttestationResponse()` or `verifyAssertionResponse()` (respectively) is called to verify
* that the response contains the signed challenge.
*
* These values only need to be persisted for `timeout` number of milliseconds (see the `generate`
* methods and their optional `timeout` parameter)
*
* 3. Authenticator Devices
*
* After an attestation, you'll need to store three things about the authenticator:
*
* - Base64-encoded "Credential ID" (varchar)
* - Base64-encoded "Public Key" (varchar)
* - Counter (int)
*
* Each authenticator must also be associated to a user so that you can generate a list of
* authenticator credential IDs to pass into `generateAssertionOptions()`, from which one is
* expected to generate an assertion response.
*/
const inMemoryUserDeviceDB = {
[loggedInUserId]: {
id: loggedInUserId,
username: `user@${rpID}`,
devices: [
/**
* {
* credentialID: string,
* publicKey: string,
* counter: number,
* }
*/
],
/**
* A simple way of storing a user's current challenge being signed by attestation or assertion.
* It should be expired after `timeout` milliseconds (optional argument for `generate` methods,
* defaults to 60000ms)
*/
currentChallenge: undefined,
},
};
/**
* Registration (a.k.a. "Attestation")
*/
app.get('/generate-attestation-options', (req, res) => {
const user = inMemoryUserDeviceDB[loggedInUserId];
const {
/**
* The username can be a human-readable name, email, etc... as it is intended only for display.
*/
username,
devices,
} = user;
const options = generateAttestationOptions({
rpName: 'SimpleWebAuthn Example',
rpID,
userID: loggedInUserId,
userName: username,
timeout: 60000,
attestationType: 'indirect',
/**
* Passing in a user's list of already-registered authenticator IDs here prevents users from
* registering the same device multiple times. The authenticator will simply throw an error in
* the browser if it's asked to perform an attestation when one of these ID's already resides
* on it.
*/
excludeCredentials: devices.map(dev => ({
id: dev.credentialID,
type: 'public-key',
transports: ['usb', 'ble', 'nfc', 'internal'],
})),
/**
* The optional authenticatorSelection property allows for specifying more constraints around
* the types of authenticators that users to can use for attestation
*/
authenticatorSelection: {
userVerification: 'preferred',
requireResidentKey: false,
},
});
/**
* The server needs to temporarily remember this value for verification, so don't lose it until
* after you verify an authenticator response.
*/
inMemoryUserDeviceDB[loggedInUserId].currentChallenge = options.challenge;
res.send(options);
});
app.post('/verify-attestation', async (req, res) => {
const { body } = req;
const user = inMemoryUserDeviceDB[loggedInUserId];
const expectedChallenge = user.currentChallenge;
let verification;
try {
verification = await verifyAttestationResponse({
credential: body,
expectedChallenge,
expectedOrigin: origin,
expectedRPID: rpID,
});
} catch (error) {
console.error(error);
return res.status(400).send({ error: error.message });
}
const { verified, authenticatorInfo } = verification;
if (verified) {
const { base64PublicKey, base64CredentialID, counter } = authenticatorInfo;
const existingDevice = user.devices.find(device => device.credentialID === base64CredentialID);
if (!existingDevice) {
/**
* Add the returned device to the user's list of devices
*/
user.devices.push({
publicKey: base64PublicKey,
credentialID: base64CredentialID,
counter,
});
}
}
res.send({ verified });
});
/**
* Login (a.k.a. "Assertion")
*/
app.get('/generate-assertion-options', (req, res) => {
// You need to know the user by this point
const user = inMemoryUserDeviceDB[loggedInUserId];
const options = generateAssertionOptions({
timeout: 60000,
allowCredentials: user.devices.map(dev => ({
id: dev.credentialID,
type: 'public-key',
transports: ['usb', 'ble', 'nfc', 'internal'],
})),
/**
* This optional value controls whether or not the authenticator needs be able to uniquely
* identify the user interacting with it (via built-in PIN pad, fingerprint scanner, etc...)
*/
userVerification: 'preferred',
});
/**
* The server needs to temporarily remember this value for verification, so don't lose it until
* after you verify an authenticator response.
*/
inMemoryUserDeviceDB[loggedInUserId].currentChallenge = options.challenge;
res.send(options);
});
app.post('/verify-assertion', (req, res) => {
const { body } = req;
const user = inMemoryUserDeviceDB[loggedInUserId];
const expectedChallenge = user.currentChallenge;
let dbAuthenticator;
// "Query the DB" here for an authenticator matching `credentialID`
for (let dev of user.devices) {
if (dev.credentialID === body.id) {
dbAuthenticator = dev;
break;
}
}
if (!dbAuthenticator) {
throw new Error('could not find authenticator matching', body.id);
}
let verification;
try {
verification = verifyAssertionResponse({
credential: body,
expectedChallenge,
expectedOrigin: origin,
expectedRPID: rpID,
authenticator: dbAuthenticator,
});
} catch (error) {
console.error(error);
return res.status(400).send({ error: error.message });
}
const { verified, authenticatorInfo } = verification;
if (verified) {
// Update the authenticator's counter in the DB to the newest count in the assertion
dbAuthenticator.counter = authenticatorInfo.counter;
}
res.send({ verified });
});
https
.createServer(
{
/**
* WebAuthn can only be run from https:// URLs. See the README on how to generate this SSL cert and key pair using mkcert
*/
key: fs.readFileSync(`./${rpID}.key`),
cert: fs.readFileSync(`./${rpID}.crt`),
},
app,
)
.listen(port, host, () => {
console.log(`🚀 Server ready at https://${host}:${port}`);
});
|