ハードウェアセキュリティキーを使うサービスを書いてみる・実装編
2026年秋にTwitter/Xの日本語圏でYubiKeyが流行っているのを眺めて、そろそろ自分でサービス側を触ってみたいなあと思い始めました。その第一歩として、以前のエントリーではWeb Authentication APIの概要をまとめRuby on Railsでの実装例を参照しました。本稿では、webauthn-rails gemを利用してサービスを書いてみます。
本稿は作業の進捗に従って更新します。
Rails Authentication system
webauthn-railsのREADMEによると、このgemはRails Authentication systemを基礎として構築されているとのこと。まずはRails 8デフォルトのauthentidation generatorを利用してパスワードでログインできるサービスを書く。
Rails new
新しいディレクトリでrailsコマンドが動くようにして対象のサービスの雛形を生成してもらう。執筆時の最新のRubyは4.0.10でした。rails newをするのも久しぶりなので、--helpで表示されたオプションから不要そうなものをskipしておく。
$ mkdir x
$ cd x
$ rbenv local 4.0.10
$ bundle init
$ bundle add rails
$ bundle exec rails new try-webauthn-rails --skip-docker --skip-ci --skip-kamal --minimal
$ cd try-webauthn-rails
$ git add .
$ git commit -m 'Run rails new'
起動するかな?デュアルスタックで起動してくるんだ。ブラウザからRailsのロゴをあしらった簡素なページを閲覧することができた。
$ bundle exec rails db:migrate
$ bundle exec rails server
:
* Listening on http://127.0.0.1:3000
* Listening on http://[::1]:3000
:
Rails generate authentidation
Rails Authentication systemのガイドSecuring Rails Applicationsに従ってユーザー、パスワード、セッションを管理する機能を生成する。
$ bundle exec rails generate authentication
$ bundle exec rails db:migrate
$ git add .
$ git commit -m 'Run rails generate authentication'
$ bundle exec rails server
localhost:3000/session/new でメールアドレスとパスワードを入力するフォームを閲覧できる。
トップページとサインアップフローの追加
Rails Authentication systemのガイドSecuring Rails Applicationsより、
After running the Authentication generator, you do need to implement your own sign up flow and add the necessary views, routes, and controller actions. There is no code generated that creates new user records and allows users to “sign up” in the first place. This is something you’ll need to wire up based on the requirements of your application.
とのこと。がんばろう。