Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
1317 lines (1227 loc) · 89.1 KB
/
Copy pathindex.html
File metadata and controls
1317 lines (1227 loc) · 89.1 KB
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<meta name="theme-color" content="#4F7DC9">
<meta charset="UTF-8">
<title>FIDO2</title>
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Code+Pro:400|Roboto:400,300,400italic,500,700|Roboto+Mono">
<link rel="stylesheet" href="//fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://storage.googleapis.com/claat-public/codelab-elements.css">
<style>
.success {
color: #1e8e3e;
}
.error {
color: red;
}
</style>
</head>
<body>
<google-codelab-analytics gaid="UA-49880327-14"></google-codelab-analytics>
<google-codelab codelab-gaid=""
id="fido2"
title="FIDO2"
environment="web"
feedback-link="">
<google-codelab-step label="はじめに" duration="0">
<h2 is-upgraded>FIDO2とはなにか?</h2>
<p>生体認証を使った本人確認などを通してログインを行いわずらわしいパスワードの入力を回避できる標準化された認証技術に、FIDO2というものがあります。この仕様は<a href="https://fidoalliance.org/" target="_blank">FIDOアライアンス</a>という団体が策定しており、仕様に準拠した認証器やサーバに対して認証を与えるといった活動を行っています。一般的に、Webサービスにユーザを登録するには、ユーザはWebサービスが提供するユーザ登録フォームに自分のEメールアドレス等をユーザIDとして入力し、送信します。その後、Webサービス側から返信されたメールに添付されたユーザ登録用ページへのリンクを開き、パスワードや個人情報を登録してユーザ登録を完了する、といったプロセスを経ます。ログイン時は、ログインページにユーザIDと登録したパスワードを入力してWebサービスにログインする、といった流れになります。このように、認証機能は「登録」フェーズと「ログイン」フェーズに分かれていますが、FIDO認証もこれと同じく「FIDO登録」と「FIDOログイン」にわかれています。これらのしくみについての概要は「<a href="https://fidoalliance.org/how-fido-works/?lang=ja" target="_blank">FIDOの仕組み</a>」を参照してください。</p>
<p>本書ではFIDO2のサーバ実装のハンズオンを通して、FIDOのしくみをコードレベルで解説します。またFIDOアライアンスは、FIDO2サーバの認証を得るためにインターネット経由でFIDO2サーバに接続し仕様に沿っているかを確認するという手順を踏みますが、正式なチェックを行う前にセルフチェックができる「FIDO Conformance Tools」というWindowsもしくはMacにインストールして利用できるツールが提供されています。その入手方法や利用方法についても解説します。</p>
<h2 is-upgraded>何を実装するか?</h2>
<p>本書では、FIDO2対応の認証器を利用するシンプルなWebベースのログインアプリを実装します。上述したように一般的に認証機能は、ユーザの「登録」と「ログイン」に分けられます。そこで本書ではこれらのフローを汎化したサンプルアプリを開発します。まずはパスワードベースのログインを行うだけの、開発のもととなるログインアプリケーションが提供されていますので、そこにFIDO2の機能を付け足す形で開発を行います。</p>
<aside class="warning"><p><strong>注意: </strong>本書で開発するものは、本番に耐えうる認証機能をすべて含んだものではありません。また完全なFIDO2サーバの仕様をすべて満たすものでもありません。FIDOアライアンスがオフィシャルに提供するFIDO2サーバの仕様を満たすかをチェックする「FIDO Conformance Tools」の入手方法とその実行方法を解説しなるべく多くのテストの成功をめざしますが、すべての機能について実装されているわけではありません。</p>
<p>また、Gmailのようなスマートフォンを持つ世界中のあらゆるユーザが登録できるWebサービスと、オンラインバンキングでの口座開設のようなユーザ登録に本人確認が必要なWebサービスとでは、登録やログインに必要なステップが異なります。そのため、「認証機能」の実装は、アプリケーションのユースケースにあわせて必要な画面構成も異なるため、注意が必要です。</p>
</aside>
<p>本ハンズオンは、Google社が提供の「<a href="https://codelabs.developers.google.com/codelabs/webauthn-reauth" target="_blank">Your First WebAuthn</a>」というFIDO2サーバ構築ハンズオンの一部を修正し、日本語で解説したものです。ハンズオンでは、<a href="https://glitch.com/" target="_blank">glitch</a>というブラウザ上で編集可能なnodejsの開発環境とサーバ環境を無料から利用できるフィリーミアムなWebサービスを利用しています。開発のベースとなるglitchのプロジェクトは、Google提供のオリジナルハンズオンのものを利用していますが、オリジナルのハンズオンのコードではエラーになるところがあるので、エラーが発生しないよう修正しています。また、FIDOアライアンスが提供するFIDO2サーバの自動チェックツール「FIDO Conformance Tools」が使えるよう、インターネット経由でREST APIアクセスを可能にしたり、URIを変更したりしています。</p>
<p>ハンズオンで開発するFIDO2サーバの開発前と開発後の画面イメージは下記のとおりです。</p>
<h2 is-upgraded>画面イメージ</h2>
<p>(開発前)<a href="https://webauthn-codelab-start.glitch.me/" target="_blank">パスワードによるログイン</a></p>
<table>
<tr><td colspan="1" rowspan="1"><p>① ユーザ名を入力してNEXTボタンを押下<br><img style="width: 260.50px" src="img/fdd15ffdecf24fd.png"></p>
</td></tr>
<tr><td colspan="1" rowspan="1"><p>② 初回登録用のパスワードを入力して「SIGN-IN」ボタンを押下<br><img style="width: 272.00px" src="img/1e3ccdac940a3fec.png"></p>
</td></tr>
<tr><td colspan="1" rowspan="1"><p>③ ホーム画面の表示<br><img style="width: 262.50px" src="img/cb7178035786a0c.png"></p>
</td></tr>
<tr><td colspan="1" rowspan="1"><p>④ 「TRY REAUTH」ボタンを押下すると画面②に移動するのでパスワードを入れて再度ログイン<br><img style="width: 272.00px" src="img/1e3ccdac940a3fec.png"></p>
</td></tr>
</table>
<p>(開発後)<a href="https://webauthn-codelab.glitch.me/" target="_blank">FIDO2によるログイン</a></p>
<aside class="warning"><p><strong>注意:</strong>リンク先のWebサービスはデバイス内蔵型のFIDO2対応認証器でのみ機能するようサーバ側に設定されています。現在では、Google社もMicrosoft社もApple社もFIDOアライアンスに参加しており、PCもスマホもほとんどのデバイスがFIDO2対応認証機を持つデバイスなので、動作可能と思われますが、注意が必要です。ちなみに、下記のキャプチャはGoogle Pixel 3a上のChromeブラウザを使ったものです。また、デバイス内蔵型のFIDO2対応認証器を利用するには、デバイスにて事前に画面ロックもしくは指紋を登録しておく必要があります。例えばPixel 3aの場合、「設定」>「セキュリティ」>「Pixel Imprint」から指紋を登録しておく必要があります。</p>
</aside>
<table>
<tr><td colspan="1" rowspan="1"><p>①ユーザ名を入力してNEXTボタンを押下<br><img style="width: 139.60px" src="img/74143d9c3b54475.png"></p>
</td><td colspan="1" rowspan="1"><p>②初回登録用パスワードを入力しSIGN-INボタンを押下<br><img style="width: 142.18px" src="img/b7705f2f73d39ccf.png"></p>
</td><td colspan="1" rowspan="1"><p>③ホーム画面表示。右下の「+」ボタンを押下<br><img style="width: 141.32px" src="img/9b833a8951d8d959.png"></p>
</td></tr>
<tr><td colspan="1" rowspan="1"><p>④指紋認証により本人確認<br>(認証器がキーペアを作成)</p>
<p class="image-container"><img style="width: 152.50px" src="img/45d0e61b1ce994b4.png"></p>
</td><td colspan="1" rowspan="1"><p>⑤キーペアの公開鍵を送信、サーバに登録</p>
<p class="image-container"><img style="width: 155.50px" src="img/f6b6b73b12b4126a.png"></p>
</td><td colspan="1" rowspan="1"><p>⑥ TRY REAUTHを押下すると再度指紋認証が求められる</p>
<p class="image-container"><img style="width: 153.73px" src="img/22423f89643dc6e6.png"></p>
</td></tr>
</table>
<aside class="warning"><p><strong>注意: </strong>上記キャプチャは、本書ハンズオンが参考にしたGoogle社が提供する「<a href="https://codelabs.developers.google.com/codelabs/webauthn-reauth" target="_blank">Your First WebAuthn</a>」というFIDO2サーバ構築ハンズオンが提供するサイトのものです。本書ハンズオンでは、Android以外のPCを含めたデバイス、Chrome以外のEdgeやSafariといったブラウザ、内蔵型でなくUSB型認証器といった様々な環境に対応するよう修正したものを構築します。</p>
</aside>
<h2 is-upgraded>認証器の種類</h2>
<p>ここでは生体認証用の認証器が、認証行為そのものとどう関係しているのかを整理します。</p>
<p>まず、IT分野における「認証」という行為は、一般的に「知識」「所有」「生体」という3つの要素の組み合わせと考えられています。IDとパスワードの組み合わせは物理的な「所有」や「生体」とは関係なく、ユーザ登録をした本人しかほぼ知り得ない「知識」をもとにした認証です。しかし、「ほぼ知り得ない」というのが問題で、フィッシングサイト等を経由して他者に盗まれたり、サーバ側で情報が漏洩したりする危険性があります。一方、公開鍵暗号化方式のキーペアを使った通信では、秘密鍵ファイルの保存管理が面倒くさいといった問題があります。</p>
<p>そのため、FIDOでは認証器なるものを用意し、その中の安全なエリアで適宜キーペアが作成され、必要に応じてその中の秘密鍵を使って署名を行ったり相手側から送信された公開鍵による署名をチェックするしくみを採用しています。認証器の重要なポイントは、どのような方法を使っても秘密鍵は取り出すことができないが署名はできる、という機能を持つことです。</p>
<p>第一段階として、この認証器をUSBドングルやNFCカードとして用意し、ユーザはそれを「所有」し、PINコードで守ることで「知識」のエッセンスを加える方式が取られました。この方式をとるものがYubico社の「<a href="https://www.yubico.com/product/security-key-by-yubico" target="_blank">Yubico Security Key</a>」や「<a href="https://www.yubico.com/product/yubikey-5ci" target="_blank">YubiKey 5Ci</a>」です。さらにこの認証器に「生体」認証のしくみを加え、キーペア作成や秘密鍵による署名、公開鍵による署名のチェックといった処理を認証器が行う前に生体認証を行う、という方式をとるものに進化しました。それを実現しているのがGoogle Pixelに同梱された生体認証による認証器やWindows PCに同梱された生体認証機能であるWindows Hello、Yubico社の「<a href="https://www.yubico.com/blog/yubico-reveals-first-biometric-yubikey-at-microsoft-ignite/" target="_blank">Yubikey Bio</a>」などです。</p>
<p>以上を認証の3要素の組み合わせと認証方式を整理すると以下の4種類に分けられます。</p>
<ol type="1" start="1">
<li>知識:パスワード認証</li>
<li>所有:PINコードや生体認証のない認証器による認証(YubiKeyの初期状態はこれ)</li>
<li>知識と所有:PINコードを設定した認証器による認証(YubiKeyに設定できる)</li>
<li>生体と所有:生体認証のついた認証器による認証(Google PixelやWindows Hello)</li>
</ol>
<p>FIDOでは上記3もしくは4を備えた認証器のことを「User Verification(ユーザ検証)」があると表現します。</p>
<p>また認証器がデバイスに内蔵されているかとりはずせるかによって「platform(内蔵された認証器を利用する場合)」と「cross-platform(取り外し可能な認証器を利用する場合)」や「internal(内蔵型)」、「usb(USBドングル型)」、「ble(ブルートゥース接続型)」、「nfc(NFC接続型)」に分けられます。これらの概念はFIDO2サーバからブラウザに利用可能な認証器のタイプを指定する際に使います。</p>
<p>ちなみに上述で画面キャプチャを紹介した「FIDO2によるログイン」では、本書のハンズオンのもととなるGoogle社のハンズオン「<a href="https://codelabs.developers.google.com/codelabs/webauthn-reauth" target="_blank">Your First WebAuthn</a>」で構築するFIDO2サーバが「User Verification(ユーザ検証)」に対応した「platform(内蔵された認証器を利用する場合)」で「internal(内蔵型)」の認証器のみ許可するよう指定しているため、これに対応したGoogle Pixel 3a上のChromeを利用しています。「cross-platform(取り外し可能な認証器を利用する場合)」型のYubiKeyではこの条件に反するため利用できないわけです。</p>
</google-codelab-step>
<google-codelab-step label="準備" duration="0">
<p>ハンズオンでは前述で紹介した <a href="https://glitch.com/" target="_blank">glitch</a> というフリーミアムなWebサービスを利用します。フリーミアムサービスであることもあり、初回の起動に時間がかかることがあります(たまにサービスがダウンしていることもありますが、<a href="https://status.glitch.com/" target="_blank">https://status.glitch.com/</a> からサービスの状態を確認することができます)。</p>
<h2 is-upgraded>ハンズオンで何を実装するか?</h2>
<ol type="1" start="1">
<li>開発前の「<a href="https://webauthn-codelab-start.glitch.me/" target="_blank">パスワードによるログイン</a>」にコードを付け足すことで、認証器を使ったパスワードレス認証を実装します。</li>
<li>オリジナルのハンズオンのFIDOサーバでは、対応認証器の条件に「User Verification」型で「platform」型の認証器(例えば、指紋認証機能付きのAndroidスマホなど)を指定していますが、本書ではあらゆるタイプの認証器に対応するよう実装します。</li>
</ol>
<h2 is-upgraded>プロジェクトを「Remix」(フォーク)</h2>
<ol type="1" start="1">
<li><a href="https://glitch.com/" target="_blank">glitch</a> にユーザ登録し、ログインします。</li>
<li><a href="https://glitch.com/edit/#!/webauthn-codelab-start" target="_blank">https://glitch.com/edit/#!/webauthn-codelab-start</a> にアクセスし、画面右上の「Remix to Edit」ボタンを押下します。これによりハンズオンのベースプロジェクトであるパスワードログインプロジェクトを自分のプロジェクトとしてフォークします。</li>
</ol>
<p class="image-container"><img style="width: 219.94px" src="img/5ab30b17250d54a7.png"></p>
<ol type="1" start="3">
<li>フォークされたプロジェクトのプロジェクト名は他とかぶらない文字列を使って勝手に生成されますが(下図の「changeable-morning-kos...」)、この文字列は修正が可能です(既存プロジェクト名とかぶらないことが条件)。</li>
</ol>
<p class="image-container"><img style="width: 203.08px" src="img/29bc8c64be37ce0b.png"> <img style="width: 201.80px" src="img/7dbed83158c70333.png"></p>
<h2 is-upgraded>ホスト名の設定</h2>
<p>フォークしたプロジェクトを編集するには、下図のように画面左側のファイルツリーから編集したいファイルを選択します。</p>
<p class="image-container"><img style="width: 330.50px" src="img/c0d70636c0574e8b.png"></p>
<p>まず .env ファイルの該当部分を下記の通り編集します。</p>
<p>.env</p>
<pre>HOSTNAME=<プロジェクト名>.glitch.me</pre>
<p>これによりブラウザから「https://<プロジェクト名>.glitch.me」にアクセスできるようになります。</p>
<aside class="warning"><p><strong>注意:</strong> ここでは「HOSTNAME=<プロジェクト名>」だけでもglichは可動しますが、後続の rpId にホスト名が FQDN でセットされる必要があるので「.glitch.com」も忘れずに追加するようにしてください。。</p>
</aside>
</google-codelab-step>
<google-codelab-step label="サーバの構成" duration="0">
<p>フォークしたプロジェクトは、nodejsのプロジェクトとして構成されており、npmというパッケージ管理ソフトで管理されています。npmでは、package.jsというファイルでインストールするパッケージやバージョンを指定します。また、本プロジェクトはExpressというWebアプリフレームワークを利用しており、外部からのアクセスはまずserver.jsで処理されます。</p>
<p>ここでは「server.js」ファイルを開いて下記の説明の該当部分を確認ください。編集は必要ありません。</p>
<p>server.js</p>
<pre>app.get('/', (req, res) => {
// Check cookie
if (req.cookies.username) {
// If user is signed in, redirect to `/reauth`.
res.redirect(307, '/reauth');
return;
}
// If user is not signed in, show `index.html` with id/password form.
res.render('index.html');
});
app.get('/home', (req, res) => {
if (!req.cookies.username ||
req.cookies['signed-in'] != 'yes') {
// If user is not signed in, redirect to `/`.
res.redirect(307, '/');
return;
}
// `home.html` shows sign-out link
res.render('home.html', {username: req.cookies.username});
});
app.get('/reauth', (req, res) => {
const username = req.cookies.username;
if (!username) {
res.redirect(302, '/');
return;
}
// Show `reauth.html`.
// User is supposed to enter a password (which will be ignored)
// Make XHR POST to `/signin`
res.render('reauth.html', {username: username});
});</pre>
<ol type="1" start="1">
<li>「/」にアクセスすると、クッキーにusernameが設定されていたら「/reauth」にリダイレクトされ、設定されていなければ「public/index.html」にリダイレクトされます。</li>
<li>「/home」にアクセスすると、クッキーにusernameがセットされ、sign-inにyesがセットされていれば「public/home.html」にアクセスされそうでなければ「/」にリダイレクトされます。</li>
<li>「/reauth」にアクセスすると、クッキーにusernameが設定されていれば「public/reauth.html」にリダイレクトされそうでなければ「/」にリダイレクトされます。</li>
</ol>
<p>server.js</p>
<pre>app.use('/auth', auth);</pre>
<p>「server.js」の後半で記述されている上記部分は、「/auth」にアクセスすると「libs/auth.js」に処理がうつることを表しており、ここではWebAuthnの仕様で規定されているREST APIを実装しています。しかしこのURIやリクエスト値のJSON形式、レスポンス値のJSON形式がFIDO2仕様と異なっており、後ほど利用する「FIDO Conformance Tools」がうまく通りません。そのため、仕様にあわせて修正を行います。また「FIDO Conformance Tools」はCSRF対応としてヘッダーに「X-Requested-With: XMLHttpRequest」をセットするといった対応はなされておらず、ログイン済みを示すためクッキーに値をセットしたりしないため、「csrfCheck」や「sessionCheck」といった処理も外します。</p>
<aside class="warning"><p><strong>注意: </strong>本番用サーバでは登録の前処理でIDとしてメールアドレスを利用し存否を確認するなどDOS攻撃を防ぐための処理を加える必要があります。</p>
</aside>
<h2 is-upgraded>① ユーザ名登録の修正</h2>
<p>こちらは「index.html」にユーザ名を入力してNEXTボタンを押下するとPOSTで呼び出される「/auth/username」のAPI実装部分であり、FIDO2サーバとは直接関係ありません。しかし、FIDO2ではユーザのクリデンシャル情報を登録依頼する際、「displayName」というパラメータが必要であるため、下記の通り追加を行います。</p>
<aside class="warning"><p><strong>注意: </strong>最初からコメントを読んで理解するのは酷なので、初回は修正後のコードを修正前のコードにまるまる上書きして進めて、動かしてみてから復習することをお勧めします。</p>
</aside>
<p>libs/auth.js</p>
<p>修正前:</p>
<pre>router.post('/username', (req, res) => {
const username = req.body.username;
// Only check username, no need to check password as this is a mock
if (!username) {
res.status(400).send({ error: 'Bad request' });
return;
} else {
// See if account already exists
let user = db.get('users')
.find({ username: username })
.value();
// If user entry is not created yet, create one
if (!user) {
user = {
username: username,
id: coerceToBase64Url(crypto.randomBytes(32), 'user.id'),
credentials: []
}
db.get('users')
.push(user)
.write();
}
// Set username cookie
res.cookie('username', username);
// If sign-in succeeded, redirect to `/home`.
res.json(user);
}
});</pre>
<p>修正後:</p>
<pre>router.post('/username', (req, res) => {
const username = req.body.username;
// Only check username, no need to check password as this is a mock
if (!username) {
res.status(400).send({ error: 'Bad request' });
return;
} else {
// See if account already exists
let user = db.get('users')
.find({ username: username })
.value();
// If user entry is not created yet, create one
if (!user) {
user = {
username: username,
displayName: username, // [追加] displayNameも保存する
id: coerceToBase64Url(crypto.randomBytes(32), 'user.id'),
credentials: []
}
db.get('users')
.push(user)
.write();
}
// Set username cookie
res.cookie('username', username);
// If sign-in succeeded, redirect to `/home`.
res.json(user);
}
});</pre>
<h2 is-upgraded>② 登録リクエストの修正</h2>
<p>FIDO2サーバの登録リクエスト処理では、クライアントからクッキー値としてusernameとdisplayNameが送信されますので、サーバ側ではランダムにチャレンジ文字列を生成しusernameに紐づけてデータベースに保存し、ブラウザが認証器に渡すためのoptionsの値を設定してクライアントに返信します。また、リクエストのクッキーにdisplayNameを追加したり、データベースに存在しないuser情報を保存する処理を追加したりといった修正点は修正後のコード内にコメントとして追加しました。</p>
<aside class="warning"><p><strong>注意: </strong>最初からコメントを読んで理解するのは酷なので、初回は修正後のコードを修正前のコードにまるまる上書きして進めて、動かしてみてから復習することをお勧めします。</p>
</aside>
<p>libs/auth.js</p>
<p>修正前:</p>
<pre>router.post('/registerRequest', csrfCheck, sessionCheck, async (req, res) => {
const username = req.cookies.username;
const user = db.get('users')
.find({ username: username })
.value();
try {
const response = await f2l.attestationOptions();
response.user = {
displayName: 'No name',
id: user.id,
name: user.username
};
response.challenge = coerceToBase64Url(response.challenge, 'challenge');
res.cookie('challenge', response.challenge);
response.excludeCredentials = [];
if (user.credentials.length > 0) {
for (let cred of user.credentials) {
response.excludeCredentials.push({
id: cred.credId,
type: 'public-key',
transports: ['internal']
});
}
}
response.pubKeyCredParams = [];
// const params = [-7, -35, -36, -257, -258, -259, -37, -38, -39, -8];
const params = [-7, -257];
for (let param of params) {
response.pubKeyCredParams.push({type:'public-key', alg: param});
}
const as = {}; // authenticatorSelection
const aa = req.body.authenticatorSelection.authenticatorAttachment;
const rr = req.body.authenticatorSelection.requireResidentKey;
const uv = req.body.authenticatorSelection.userVerification;
const cp = req.body.attestation; // attestationConveyancePreference
let asFlag = false;
if (aa && (aa == 'platform' || aa == 'cross-platform')) {
asFlag = true;
as.authenticatorAttachment = aa;
}
if (rr && typeof rr == 'boolean') {
asFlag = true;
as.requireResidentKey = rr;
}
if (uv && (uv == 'required' || uv == 'preferred' || uv == 'discouraged')) {
asFlag = true;
as.userVerification = uv;
}
if (asFlag) {
response.authenticatorSelection = as;
}
if (cp && (cp == 'none' || cp == 'indirect' || cp == 'direct')) {
response.attestation = cp;
}
res.json(response);
} catch (e) {
res.status(400).send({ error: e });
}
});</pre>
<p>修正後:</p>
<pre>// [修正1] URIを変更し、csrfCheckとsessionCheckを削除
router.post('/attestation/options', async (req, res) => {
const username = req.body.username; // [修正2] usernameをbodyから取得
const displayName = req.body.displayName; // [修正3] displayNameを追加
// [修正4] userは後ほど修正が入るため、型をconstからletに変更
let user = db.get('users')
.find({ username: username })
.value();
// [修正5] ユーザがいなければDBに追加
if (!user) {
user = {
username: username,
displayName: displayName,
id: coerceToBase64Url(crypto.randomBytes(32), 'user.id'),
credentials: []
}
db.get('users')
.push(user)
.write();
}
try {
const response = await f2l.attestationOptions();
response.user = {
displayName: user.displayName, // [修正6] displayNameをセット
id: user.id,
name: user.username
};
res.cookie('username', user.username); // [修正6] usernameをcookieにセット
response.challenge = coerceToBase64Url(response.challenge, 'challenge');
res.cookie('challenge', response.challenge);
response.excludeCredentials = [];
if (user.credentials.length > 0) {
for (let cred of user.credentials) {
response.excludeCredentials.push({
id: cred.credId,
type: 'public-key',
// [修正7] 認証器タイプに、"usb", "nfc", "ble"を追加
transports: ['internal','usb','nfc','ble']
});
}
}
response.pubKeyCredParams = [];
// const params = [-7, -35, -36, -257, -258, -259, -37, -38, -39, -8];
const params = [-7, -257];
for (let param of params) {
response.pubKeyCredParams.push({type:'public-key', alg: param});
}
// [修正8] リクエストにauthenticatorSelectionがセットされているかチェック
if(req.body.authenticatorSelection) {
const as = {}; // authenticatorSelection
const aa = req.body.authenticatorSelection.authenticatorAttachment;
const rr = req.body.authenticatorSelection.requireResidentKey;
const uv = req.body.authenticatorSelection.userVerification;
let asFlag = false;
if (aa && (aa == 'platform' || aa == 'cross-platform')) {
asFlag = true;
as.authenticatorAttachment = aa;
}
// [修正9] rrの存否チェックロジックを修正
if ((rr !== undefined) && typeof rr == 'boolean') {
asFlag = true;
as.requireResidentKey = rr;
}
if (uv && (uv == 'required' || uv == 'preferred' || uv == 'discouraged')) {
asFlag = true;
as.userVerification = uv;
}
if (asFlag) {
response.authenticatorSelection = as;
}
}
// [修正9] 修正8のロジック追加に伴い、cp部分を移動
const cp = req.body.attestation; // attestationConveyancePreference
if (cp && (cp == 'none' || cp == 'indirect' || cp == 'direct')) {
response.attestation = cp;
}
// [修正10] extensionsを追加
const ex = req.body.extensions;
if (ex) {
response.extensions = ex;
}
// [修正11] statusとerrorMessageをレスポンスに追加
response.status = 'ok';
response.errorMessage = "";
res.json(response);
} catch (e) {
// [修正12] エラー時のresponseを修正
res.status(400).send({status:"failed",
errorMessage:"/attestation/options: "+e.message});
}
});</pre>
<h2 is-upgraded>③ 登録処理の修正</h2>
<p>FIDO2サーバの登録処理では、前述の登録リクエストで返されたoptions(ユーザIDやチャレンジ文字列がセット)を受けたブラウザは、「navigator.credentials.create(options)」というFIDO2対応のJavaScriptを実行し、ユーザIDに紐付いたキーペアを作成し、その公開鍵等をセットしたattestation値をFIDOサーバに送信します。FIDO2サーバはここで実装する登録処理で受領したattestationから公開鍵を取り出し、該当するユーザと紐づけてデータベースに保存します。</p>
<aside class="warning"><p><strong>注意: </strong>最初からコメントを読んで理解するのは酷なので、初回は修正後のコードを修正前のコードにまるまる上書きして進めて、動かしてみてから復習することをお勧めします。</p>
</aside>
<p>libs/auth.js</p>
<p>修正前:</p>
<pre>router.post('/registerResponse', csrfCheck, sessionCheck, async (req, res) => {
const username = req.cookies.username;
const challenge = coerceToArrayBuffer(req.cookies.challenge, 'challenge');
const credId = req.body.id;
const type = req.body.type;
try {
const clientAttestationResponse = { response: {} };
clientAttestationResponse.rawId =
coerceToArrayBuffer(req.body.rawId, "rawId");
clientAttestationResponse.response.clientDataJSON =
coerceToArrayBuffer(req.body.response.clientDataJSON, "clientDataJSON");
clientAttestationResponse.response.attestationObject =
coerceToArrayBuffer(req.body.response.attestationObject, "attestationObject");
let origin = '';
if (req.get('User-Agent').indexOf('okhttp') > -1) {
const octArray = process.env.ANDROID_SHA256HASH.split(':').map(h => parseInt(h, 16));
const androidHash = coerceToBase64Url(octArray, 'Android Hash');
origin = `android:apk-key-hash:${androidHash}`; // TODO: Generate
} else {
origin = `https://${req.get('host')}`;
}
const attestationExpectations = {
challenge: challenge,
origin: origin,
factor: "either"
};
const regResult = await f2l.attestationResult(clientAttestationResponse, attestationExpectations);
const credential = {
credId: coerceToBase64Url(regResult.authnrData.get("credId"), 'credId'),
publicKey: regResult.authnrData.get("credentialPublicKeyPem"),
aaguid: coerceToBase64Url(regResult.authnrData.get("aaguid"), 'aaguid'),
prevCounter: regResult.authnrData.get("counter")
};
const user = db.get('users')
.find({ username: username })
.value();
user.credentials.push(credential);
db.get('users')
.find({ username: username })
.assign(user)
.write();
res.clearCookie('challenge');
// Respond with user info
res.json(user);
} catch (e) {
res.clearCookie('challenge');
res.status(400).send({ error: e.message });
}
});</pre>
<p>修正後:</p>
<pre>// [修正1] URIを変更し、csrfCheckとsessionCheckを削除
const base64url = require('base64url');
router.post('/attestation/result', async (req, res) => {
const username = req.cookies.username;
const challenge = coerceToArrayBuffer(req.cookies.challenge, 'challenge');
const credId = req.body.id;
const type = req.body.type;
try {
if(!req.body.id || typeof req.body.id != 'string') { //[修正2]idをチェック
throw Error("Not adequate user id");
} else if(req.body.id != req.body.rawId) { //[修正3]idとrawIdが同じかチェック
throw Error("User id and rawId is different.");
}
if(!req.body.type || req.body.type != 'public-key') { //[修正4]typeをチェック
throw Error("'type' is not 'public-key'");
}
//[修正5]clientDataJSON.originがnullでなくstringであることをチェック
let clientDataJSON = JSON.parse(base64url.decode(req.body.response.clientDataJSON));
if(!clientDataJSON.origin || typeof clientDataJSON.origin != 'string') {
throw Error("clientDataJSON.origin should be string");
}
const clientAttestationResponse = { response: {} };
clientAttestationResponse.rawId =
coerceToArrayBuffer(req.body.rawId, "rawId");
clientAttestationResponse.response.clientDataJSON =
coerceToArrayBuffer(req.body.response.clientDataJSON, "clientDataJSON");
clientAttestationResponse.response.attestationObject =
coerceToArrayBuffer(req.body.response.attestationObject, "attestationObject");
let origin = '';
if (req.get('User-Agent').indexOf('okhttp') > -1) {
const octArray = process.env.ANDROID_SHA256HASH.split(':').map(h => parseInt(h, 16));
const androidHash = coerceToBase64Url(octArray, 'Android Hash');
origin = `android:apk-key-hash:${androidHash}`; // TODO: Generate
} else {
origin = `https://${req.get('host')}`;
}
//[修正6]clientDataJSON.originとoriginが同一であることのチェック
if(clientDataJSON.origin != origin) {
throw Error("clientDataJSON.origin and origin should be same.");
}
const attestationExpectations = {
challenge: challenge,
origin: origin,
factor: "either"
};
//[修正7] デバッグのため、f2l.attestationResultの例外処理を追加
let regResult;
try {
regResult = await f2l.attestationResult(clientAttestationResponse, attestationExpectations);
} catch(e) {
console.log(e.message);
throw e;
}
const credential = {
credId: coerceToBase64Url(regResult.authnrData.get("credId"), 'credId'),
publicKey: regResult.authnrData.get("credentialPublicKeyPem"),
aaguid: coerceToBase64Url(regResult.authnrData.get("aaguid"), 'aaguid'),
prevCounter: regResult.authnrData.get("counter")
};
const user = db.get('users')
.find({ username: username })
.value();
user.credentials.push(credential);
db.get('users')
.find({ username: username })
.assign(user)
.write();
res.clearCookie('challenge');
// Respond with user info
// [修正8] statusとerrorMessageをレスポンスに追加
user.status = "ok";
user.errorMessage = "";
res.json(user);
} catch (e) {
res.clearCookie('challenge');
// [修正9] エラー時のresponseを修正
res.status(400).send({status:"failed",
errorMessage:"/attestation/result: "+e.message});
}
});</pre>
<p>上記コードをコピーすると「const base64url = require('base64url');」部分でエラーになると思いますが、これはnpmのパッケージにbase64urlというものがインストールされていないことが理由です。npmパッケージは「package.json」に設定しますので、「package.json」を開いて下記の通り「"dependencies" : {」の下部に「"base64url": "^3.0.1",」を追記します。ファイルを保存するとglitchが勝手にnpmパッケージをダウンロード・インストールしてくれます。</p>
<p>package.json</p>
<pre>{
"name": "webauthn-codelab",
"version": "0.0.1",
"description": "A simple Node app built on Express, instantly up and running.",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"base64url": "^3.0.1",
"express": "^4.16.4",
"hbs": "^4.0.4",
"cookie-parser": "^1.4.4",
"lowdb": "^1.0.0",
"crypto": "^1.0.1",
"fido2-lib": "agektmr/fido2-lib#android-compatible3"
},
"engines": {
"node": "8.x"
},
"repository": {
"url": "https://glitch.com/edit/#!/hello-express"
},
"license": "MIT",
"keywords": [
"node",
"glitch",
"express"
]
}</pre>
<h2 is-upgraded>④ 認証依頼処理の修正</h2>
<p>FIDO2サーバの認証依頼処理では、クライアント側からユーザ名(username)とローカルに保存したクリデンシャルID(credId)が送信されますので、サーバ側ではユーザ名をもとにデータベースを検索してその存否を確認します。存在しなければ認証できませんのでその旨を返します。ユーザが存在していたら、そのユーザに紐付いたクリデンシャルが保存されているかをクライアントから送信されたクリデンシャルIDをキーにして検索し、存在していればそれを返信のため、allowCredentialsという配列にセットします。サーバから返信する値はassertionオプションと呼ばれ、そこに認証時に使うチャレンジ文字列や前述のallowCredentials配列をセットしてクライアントに返します。</p>
<aside class="warning"><p><strong>注意: </strong>最初からコメントを読んで理解するのは酷なので、初回は修正後のコードを修正前のコードにまるまる上書きして進めて、動かしてみてから復習することをお勧めします。</p>
</aside>
<p>libs/auth.js</p>
<p>修正前:</p>
<pre>router.post('/signinRequest', csrfCheck, async (req, res) => {
try {
const user = db.get('users')
.find({ username: req.cookies.username })
.value();
if (!user) {
// Send empty response if user is not registered yet.
res.json({error: 'User not found.'});
return;
}
const credId = req.query.credId;
const response = await f2l.assertionOptions();
// const response = {};
response.userVerification = req.body.userVerification || 'required';
response.challenge = coerceToBase64Url(response.challenge, 'challenge');
res.cookie('challenge', response.challenge);
response.allowCredentials = [];
for (let cred of user.credentials) {
// When credId is not specified, or matches the one specified
if (!credId || cred.credId == credId) {
response.allowCredentials.push({
id: cred.credId,
type: 'public-key',
transports: ['internal']
});
}
}
res.json(response);
} catch (e) {
res.status(400).json({ error: e });
}
});</pre>
<p>修正後:</p>
<pre>router.post('/assertion/options', async (req, res) => {
try {
const user = db.get('users')
.find({ username: req.cookies.username })
.value();
if (!user) {
// Send empty response if user is not registered yet.
res.json({error: 'User not found.'});
return;
}
const credId = req.query.credId;
const response = await f2l.assertionOptions();
// const response = {};
response.userVerification = req.body.userVerification || 'required';
response.challenge = coerceToBase64Url(response.challenge, 'challenge');
res.cookie('challenge', response.challenge);
response.allowCredentials = [];
for (let cred of user.credentials) {
// When credId is not specified, or matches the one specified
if (!credId || cred.credId == credId) {
response.allowCredentials.push({
id: cred.credId,
type: 'public-key',
transports: ['internal','usb','nfc','ble'] // [修正1] usb", "nfc", "ble"を追加
});
}
}
// [修正2] extensionsを追加
const ex = req.body.extensions;
if (ex) {
response.extensions = ex;
}
// [修正3] statusとerrorMessageをレスポンスに追加
response.status = "ok";
response.errorMessage = "";
res.json(response);
} catch (e) {
// [修正4] エラー時のresponseを修正
res.status(400).send({status:"failed",
errorMessage:"/assertion/options: "+e.message});
}
});</pre>
<p>⑤ 認証処理の修正</p>
<p>FIDO2サーバの認証処理では、クライアントから送信されるFIDO2認証に必要な署名情報を受領します。そして、サーバ側に保存されたユーザの公開鍵と認証依頼処理で作成したチャレンジ文字列、サーバのホスト名(FQDN)で構成されるorigin値といった値から構成されるassertionExpectation(認証の期待値)と、クライアントから受領した公開鍵のID(rawID)やクライアント側が認識するチャレンジ文字列とorigin値などを含むclientDataJSON、クライアント側で署名した情報を含むauthenticatorDataといった値を含むclientAssertionResponseとを比較して正しい署名情報かをチェックします。</p>
<aside class="warning"><p><strong>注意: </strong>最初からコメントを読んで理解するのは酷なので、初回は修正後のコードを修正前のコードにまるまる上書きして進めて、動かしてみてから復習することをお勧めします。</p>
</aside>
<p>libs/auth.js</p>
<p>修正前:</p>
<pre>router.post('/signinResponse', csrfCheck, async (req, res) => {
// Query the user
const user = db.get('users')
.find({ username: req.cookies.username })
.value();
let credential = null;
for (let cred of user.credentials) {
if (cred.credId === req.body.id) {
credential = cred;
}
}
try {
if (!credential) {
throw 'Authenticating credential not found.';
}
const challenge = coerceToArrayBuffer(req.cookies.challenge, 'challenge');
const origin = `https://${req.get('host')}`; // TODO: Temporary work around for scheme
const clientAssertionResponse = { response: {} };
clientAssertionResponse.rawId =
coerceToArrayBuffer(req.body.rawId, "rawId");
clientAssertionResponse.response.clientDataJSON =
coerceToArrayBuffer(req.body.response.clientDataJSON, "clientDataJSON");
clientAssertionResponse.response.authenticatorData =
coerceToArrayBuffer(req.body.response.authenticatorData, "authenticatorData");
clientAssertionResponse.response.signature =
coerceToArrayBuffer(req.body.response.signature, "signature");
clientAssertionResponse.response.userHandle =
coerceToArrayBuffer(req.body.response.userHandle, "userHandle");
const assertionExpectations = {
challenge: challenge,
origin: origin,
factor: "either",
publicKey: credential.publicKey,
prevCounter: credential.prevCounter,
userHandle: coerceToArrayBuffer(user.id, 'userHandle')
};
const result = await f2l.assertionResult(clientAssertionResponse, assertionExpectations);
credential.prevCounter = result.authnrData.get("counter");
db.get('users')
.find({ id: req.cookies.id })
.assign(user)
.write();
res.clearCookie('challenge');
res.cookie('signed-in', 'yes');
res.json(user);
} catch (e) {
res.clearCookie('challenge');
res.status(400).json({ error: e });
}
});</pre>
<p>修正後:</p>
<pre>router.post('/assertion/result', async (req, res) => {
try {
//[修正1]typeをチェック
if(!req.body.type || req.body.type != 'public-key') {
throw Error("'type' is not 'public-key'");
}
// Query the user
const user = db.get('users')
.find({ username: req.cookies.username })
.value();
let credential = null;
for (let cred of user.credentials) {
if (cred.credId === req.body.id) {
credential = cred;
}
}
if (!credential) {
throw 'Authenticating credential not found.';
}
const challenge = coerceToArrayBuffer(req.cookies.challenge, 'challenge');
const origin = `https://${req.get('host')}`; // TODO: Temporary work around for scheme
const clientAssertionResponse = { response: {} };
clientAssertionResponse.rawId =
coerceToArrayBuffer(req.body.rawId, "rawId");
clientAssertionResponse.response.clientDataJSON =
coerceToArrayBuffer(req.body.response.clientDataJSON, "clientDataJSON");
clientAssertionResponse.response.authenticatorData =
coerceToArrayBuffer(req.body.response.authenticatorData, "authenticatorData");
clientAssertionResponse.response.signature =
coerceToArrayBuffer(req.body.response.signature, "signature");
clientAssertionResponse.response.userHandle =
coerceToArrayBuffer(req.body.response.userHandle, "userHandle");
const assertionExpectations = {
challenge: challenge,
origin: origin,
factor: "either",
publicKey: credential.publicKey,
prevCounter: credential.prevCounter,
userHandle: coerceToArrayBuffer(user.id, 'userHandle')
};
//[修正2] デバッグのため、f2l.assertionResultの例外処理を追加
let result;
try {
result = await f2l.assertionResult(clientAssertionResponse, assertionExpectations);
} catch(e) {
console.log("f2l.assertionResult: "+e.message);
throw e;
}
credential.prevCounter = result.authnrData.get("counter");
db.get('users')
.find({ id: req.cookies.id })
.assign(user)
.write();
res.clearCookie('challenge');
res.cookie('signed-in', 'yes');
// [修正3] statusとerrorMessageをレスポンスに追加
user.status = "ok";
user.errorMessage = "";
res.json(user);
} catch (e) {
res.clearCookie('challenge');
// [修正4] エラー時のresponseを修正
res.status(400).send({status:"failed",
errorMessage:"/assertion/result: "+e.message});
}
});</pre>
</google-codelab-step>
<google-codelab-step label="Webアプリの作成: 登録" duration="0">
<p>「サーバの構成」では、FIDO2サーバのREST API部分である「auth.js」のソースコードの修正を行いましたが、「Webアプリの作成」では「public/client.js」を編集し、必要なロジックを追加していきます。また、FIDO2サーバがブラウザに提供するHTMLファイルは「views」フォルダ配下に配置されており、ユーザ名入力画面が「views/index.html」、パスワード入力画面が「views/reauth.html」、ホーム画面が「views/home.html」ですので、こちらにもFIDO2認証に対応するためのUIやロジックを追加していきます。</p>
<p>ここで実装する「登録」では、ホーム画面の右下にFABボタンを用意してユーザの認証器が作成するキーペアの公開鍵を登録できるよう実装します。</p>
<h2 is-upgraded>registerCredential() 関数の追加</h2>
<p>home画面に実装するFABボタンのクリック時に呼び出される関数 registerCredential() を「public/client.js」に実装していきます。</p>
<p>public/client.js<br>コメント「// 6. Register the credential to the server endpoint: `/auth/registerResponse`」の下部に下記コードを追記</p>
<pre>export const registerCredential = async (opts) => {
// ここに以下に説明するコードを追記します。
// ①ブラウザのWebAuthn対応チェック
// ②サーバのAPIエンドポイントからoptionsを取得
// ③クリデンシャルの作成
// ④サーバのAPIエンドポイントにクリデンシャルを登録
};</pre>
<aside class="warning"><p><strong>注意</strong>: この関数はJavaScriptモジュールとして利用するため、関数定義の前にexportを付与します。また、非同期を表すasyncとして定義しているため、関数内では非同期関数の実行にawaitを宣言して、その完了を待つことができるようになります。</p>
</aside>
<h2 is-upgraded>①ブラウザのWebAuthn対応チェック</h2>
<p>まずはじめにブラウザがWebAuthnに対応しているかをチェックします。そのチェックのためにwindow.PublicKeyCredential を実行し、WebAuthnに対応していなければ例外を投げます。</p>
<p>public/client.js<br>上記registerCredential関数の中のコメント①の下部に追記</p>
<pre>if (!window.PublicKeyCredential) {
throw 'WebAuthn not supported on this browser.';
}</pre>
<h2 is-upgraded>②サーバのAPIエンドポイントからoptionsを取得</h2>
<p>認証器にキーペアの生成を依頼する前に、サーバにチャレンジ文字列とその他のパラメータの生成を依頼し、取得します。そのためにAPIを実行する関数 _fetch() を opts を引数に実行し、サーバにPOSTでリクエストを送信します。</p>
<p>public/client.js<br>上記registerCredential関数の中のコメント②の下部に追記</p>
<pre>const options = await _fetch('/auth/attestation/options', opts);</pre>
<aside class="special"><p><strong>ノート</strong>: 関数 _fetch() は application/json 型のオプションをbodyにセットしてPOSTで送信するよう実装されています。またサーバからJSON値が返信されoptionsにセットします。</p>
</aside>
<p>上記の処理でクライアントがサーバから取得するoptions はWebAuthn仕様で規定されている <a href="https://www.w3.org/TR/webauthn/#dictdef-publickeycredentialcreationoptions" target="_blank">PublicKeyCredentialCreationOptions</a> にのっとって作成されます。optionsは下記のような構造をしています。</p>
<pre>{
"rp": {
"name": "WebAuthn Codelab",
"id": "webauthn-codelab.glitch.me"
},
"user": {
"displayName": "Test",
"id": "...",
"name": "test"
},
"challenge": "...",
"pubKeyCredParams": [
{
"type": "public-key",
"alg": -7
}, {
"type": "public-key",
"alg": -257
}
],
"timeout": 1800000,
"attestation": "none",
"excludeCredentials": [
{
"id": "...",
"type": "public-key",
"transports": [
"internal"
]
}
],
"authenticatorSelection": {
"authenticatorAttachment": "platform",
"userVerification": "required"
}
}</pre>
<h2 is-upgraded>③クリデンシャルの作成</h2>
<p>上記のoptionsはHTTP送信されるためエンコードされているため、user.id と challenge と excludeCredentials に含まれる ids といったパラメータはバイナリにデコードします。</p>
<p>public/client.js<br> 上記registerCredential関数の中のコメント③の下部に追記</p>
<pre>options.user.id = window.base64url.decode(options.user.id);
options.challenge = window.base64url.decode(options.challenge);
if (options.excludeCredentials) {
for (let cred of options.excludeCredentials) {
cred.id = window.base64url.decode(cred.id);
}
}
const cred = await navigator.credentials.create({
publicKey: options
});</pre>
<p>その後、navigator.credentials.create() を実行して、認証器に新しいクリデンシャルの生成を依頼します。今回は「Virtual Authenticator Tab」で生成したAuthenticatorが自動的にクリデンシャルを生成し、リストに追加します。生成されたクリデンシャル(cred)は、このあと登録のためサーバに送信されます。</p>
<h2 is-upgraded>④サーバのAPIエンドポイントにクリデンシャルを登録</h2>
<p>クリデンシャルオブジェクトは以下のような形をしています。</p>
<pre>{
"id": "...",
"rawId": "...",
"type": "public-key",
"response": {
"clientDataJSON": "...",
"attestationObject": "..."
}
}</pre>
<p>クリデンシャル作成前に取得したオプションと同じく、クリデンシャルのいくつかのバイナリパラメータは文字列としてサーバに送信するためエンコードが必要です。またクリデンシャルIDはローカル保存し、登録したIDをもとに認証できるようにします。最後にクリデンシャルオブジェクトをサーバに送信し、HTTPコードが200で返ってきたら登録に成功したことを表します。</p>
<p>public/client.js<br> 上記registerCredential関数の中のコメント④の下部に追記</p>
<pre>const credential = {};
credential.id = cred.id;
credential.rawId = window.base64url.encode(cred.rawId);
credential.type = cred.type;
if (cred.response) {
const clientDataJSON =
window.base64url.encode(cred.response.clientDataJSON);
const attestationObject =
window.base64url.encode(cred.response.attestationObject);
credential.response = {
clientDataJSON,
attestationObject
};
}
localStorage.setItem(`credId`, credential.id);
return await _fetch('/auth/attestation/result' , credential);</pre>
</google-codelab-step>
<google-codelab-step label="Webアプリの作成: 登録画面" duration="0">
<p>ホーム画面「views/home.html」にクリデンシャルを登録するFABボタンと登録されたクリデンシャルのリストと削除ボタンを追加します。</p>
<h2 is-upgraded>① UI部分の実装</h2>
<p>このあと追加する getCredentials 関数で設定する ul#list に登録されたクリデンシャルが <div id="list"></div> 部分にリスト表示されます。その後に設定した <button id="register" ...> はFABボタンを表し、ボタンを押下するとあとで追加する register 関数が実行されます。</p>
<p>views/home.html<br>コメント「1. Build UI placeholder -->」の下部に下記コードを追記</p>
<pre><h3 class="mdc-typography mdc-typography--headline6">
Your registered credentials:
</h3>
<section>
<div id="list"></div>
<button id="register" class="mdc-fab mdc-ripple-upgraded">
<i class="mdc-fab__icon material-icons">+</i>
</button>
</section></pre>
<h2 is-upgraded>② クリデンシャルのリストを生成する getCredentials 関数</h2>
<p>ul#list にクリデンシャルリストを表示するHTML値をセットします。最後に「getCredentials();」を記述することで、「/home」にアクセスしたときにクリデンシャルリストが表示されるようになります。</p>
<p>views/home.html<br>コメント「// 2. Get a list of credentials and display: `getCredentials()`」下部に以下コードを追記</p>
<pre>const getCredentials = async () => {
const res = await _fetch('/auth/getKeys');
const list = document.querySelector('#list');
if (res.credentials.length === 0) {
list.innerHTML = '<div>No credentials found.</div>';
return;
}
const creds = html`${repeat(res.credentials, cred => cred.credId,(cred, index) =>
html`<div class="mdc-card credential">
<span class="mdc-typography mdc-typography--body2">${cred.credId}</span>
<pre class="public-key">${cred.publicKey}</pre>
<div class="mdc-card__actions">
<button id="${cred.credId}" class="mdc-button mdc-button--raised" @click="${removeCredential}">Remove</button>
</div>
</div>`)}`;
render(creds, list);
};
getCredentials();</pre>
<aside class="special"><p><strong>ノート</strong>: "<a href="https://lit-html.polymer-project.org/" target="_blank">lit-html</a>"というHTMLテンプレートライブラリを利用しています。</p>
</aside>
<h2 is-upgraded>③ クリデンシャルを削除する removeCredential 関数</h2>
<p>クリデンシャルのリストにはそれぞれ「remove」ボタンが作成され、ボタンを押下すると credId を引数に /auth/removeKey が呼ばれ、該当のクリデンシャルが削除されます。</p>
<p>public/client.js</p>
<p>コメント「// 3. Remove the credential: `removeCredential()`」の下部に追記</p>
<pre>export const unregisterCredential = async (credId) => {
localStorage.removeItem('credId');
return _fetch(`/auth/removeKey?credId=${encodeURIComponent(credId)}`);
};</pre>
<p>views/home.html<br>コメント「// 3. Remove the credential: `removeCredential()`」の下部に追記</p>
<pre>import { unregisterCredential } from '/client.js';
const removeCredential = async e => {
try {
await unregisterCredential(e.target.id);
location.reload();
} catch (e) {
alert(e);
}
};</pre>
<h2 is-upgraded>④ クリデンシャルの登録</h2>
<p>最後に「+」のFABボタンが押下されると、新規クリデンシャルを登録するために registerCredential() 関数を実行します。</p>
<p>views/home.html<br>コメント「// 4. Register a credential」の下部に追記</p>
<pre>import { registerCredential } from '/client.js';
const register = document.querySelector("#register");
register.addEventListener("click", e => {
registerCredential({
username: "{{username}}", // TODO usernameを追加
displayName: "{{username}}", // TODO displayNameを追加
attestation: "none",
authenticatorSelection: {
// authenticatorAttachment: "cross-platform",
userVerification: "preferred",
requireResidentKey: false
}
}).then(user => {
location.reload();
}).catch(e => alert(e));
});</pre>
<p>registerCredential() 関数の引数は <a href="https://www.w3.org/TR/webauthn/#dictdef-publickeycredentialcreationoptions" target="_blank">PublicKeyCredentialCreationOptions</a> の形式をとりますが、詳細は下記のとおりです。</p>
<table>