WebSurfer's Home

トップ > Blog 1   |   ログイン
APMLフィルター

MVC5 アプリで Google Authenticator による 2FA

by WebSurfer 2021年11月4日 15:27

先の記事「MVC5 アプリに 2 要素認証を実装」で SMS と Email を利用した 2 要素認証の実装に関する記事を書きました。この記事にはそれに認証アプリ Google Authenticator App を利用した 2 要素認証を追加する話を書きます。

Google Authenticator

認証アプリは Google Authenticator App でなければならないという訳ではなく、TOTP (Time-based One-time Password Algorithm) ベースの認証アプリであれば Microsoft Authenticator App なども使えるそうですが、今回は Google Authenticator App を使ってみました。

まず、TOTP というのがどういう仕組みかですが、ITmedia NEWS の記事「SMS認証の仕組みと危険性、「TOTP」とは? 「所有物認証」のハナシ」が分かりやすいと思いますので見てください。リンク切れになると困るので図だけ借用して下に貼っておきます。

Time-based One-time Password Algorithm

今回の ASP.NET MVC5 アプリのケースで説明します。まず、ASP.NET MVC5 アプリ(上の図で「認証サーバ」と書いてあるもの)が発行する秘密キーを Google Authenticator App(上の図で「ソフトウェアトークン」と書いてあるもの)に取得させ共有します。秘密キーは ASP.NET MVC5 アプリに登録されたユーザー毎に異なる 32 文字の文字列です。Google Authenticator App は、そのユーザーが保有するスマートフォンにインストールされていることが前提です。

この記事の一番上にある画像は ASP.NET MVC5 アプリが表示した画面で、それからスマートフォンの Google Authenticator App に秘密キーを共有させます。表示されている QR コードをスキャンするか、「3. QR コードが読めない場合」の下に表示されている 32 文字を手入力することによって共有できます。

その機密キー(上の図で「シード」と書いてあるもの)と時刻を元に、TOTP アルゴリズムで 6 桁の数字のパスワードを計算します。時刻を計算に使うところが Time-based ということだそうです。

さらに 30 秒ごとに計算し直すので、パスワードは 30 秒ごとに違った数字になります。それが One-time ということだそうです。

Google Authenticator App はスタンドアロンで動いています。ASP.NET MVC5 アプリ他どことも通信していませんが秘密キーとスマートフォンの内部時刻でパスワードは計算できます。

秘密キーは共有しているので、ASP.NET MVC5 アプリと Google Authenticator App が取得する時刻が正確に一致していれば、計算で求めたパスワードは両方で同じになります。

という訳で、2 要素認証が必要になっている ASP.NET MVC5 アプリから TOTP ベースのパスワードを求められたら、Google Authenticator App を立ち上げて表示されたパスワードを入力すればログインできるという仕組みになっています。

TOPT ベースの 2 要素認証は Visual Studio のテンプレートで作った MVC5 プロジェクトには実装されておらず、ゼロから作っていくことになります。先人の例がないかググって調べてみましたら、Using Google Authenticator with ASP.NET Identity という記事(以下、参考記事と言います)がありましたので参考にさせていただきました。

以下に実装手順を書きます。参考記事には書いてないが必須な実装は補足・追記しました。また、QR コードがスキャンできない場合の対応など参考記事とは違う実装にしている点もあります。

(1) プロジェクトの作成

プロジェクトの作成方法は先の記事「MVC5 アプリに 2 要素認証を実装」を見てください。それに Google Authenticator App 利用の 2 要素認証を追加で実装します。

まず、TOTP 用の秘密キーの生成やユーザーが入力したパスワードの検証を行うためのライブラリ OtpSharp を NuGet からインストールします。Base32 という NuGet パッケージも必要ですが一緒にインストールされるはずです。

OtpSharp をインストール

(2) ApplicationUser クラスにプロパティ追加

Models/IdentityModel.cs ファイルの ApplicationUser クラスに以下の 2 つのプロパティを追加します。

public class ApplicationUser : IdentityUser
{
    // Google Authnticator による 2FA を実装するため追加
    public bool IsGoogleAuthenticatorEnabled { get; set; }
    public string GoogleAuthenticatorSecretKey { get; set; }

    // 以下は既存のコード
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(
                           UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, 
                    DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

Migration 操作によって既存の SQL Server データベースの AspNetUsers テーブルに同名の列が追加されます。アプリを実行して Google Authenticator を有効にすると、IsGoogleAuthenticatorEnabled 列は True になり、GoogleAuthenticatorSecretKey には秘密キーが自動生成され格納されます。

(3) トークンプロバイダの作成

Google Authenticator を使った 2 要素認証用のプロバイダを作成します。(SMS と Email を使った 2 要素認証用のプロバイダは既存です)

IUserTokenProvider<TUser, TKey> インターフェイスを継承した GoogleAuthenticatorTokenProvider クラスを以下のように作成します。クラスファイルは MfaTokenProvider というフォルダを作ってそこに置きました。

using MVC5TwoFactorAuth.Models;
using Microsoft.AspNet.Identity;
using System.Threading.Tasks;
using OtpSharp;
using Base32;

namespace MVC5TwoFactorAuth.MfaTokenProvider
{
    public class GoogleAuthenticatorTokenProvider 
        : IUserTokenProvider<ApplicationUser, string>
    {
        public Task<string> GenerateAsync(string purpose, 
                                          UserManager<ApplicationUser, string> manager, 
                                          ApplicationUser user)
        {
            return Task.FromResult((string)null);
        }

        public Task<bool> IsValidProviderForUserAsync(UserManager<ApplicationUser, string> manager, 
                                                      ApplicationUser user)
        {
            return Task.FromResult(user.IsGoogleAuthenticatorEnabled);
        }

        public Task NotifyAsync(string token, 
                                UserManager<ApplicationUser, string> manager, 
                                ApplicationUser user)
        {
            return Task.FromResult(true);
        }

        public Task<bool> ValidateAsync(string purpose, 
                                        string token, 
                                        UserManager<ApplicationUser, string> manager, 
                                        ApplicationUser user)
        {
            long timeWindowUsed = 0;

            var otp = new Totp(Base32Encoder.Decode(user.GoogleAuthenticatorSecretKey));

            bool valid = otp.VerifyTotp(token, 
                                        out timeWindowUsed, 
                                        new VerificationWindow(previous: 1, future: 1));

            return Task.FromResult(valid);
        }
    }
}

ValidateAsync メソッドで使われている OtpSharp ライブラリの説明は GitHub の記事Otp.NET にあります。

VerifyTotp メソッドの第 1 引数 token はユーザーが Google Authenticator App より取得して入力した 6 桁の数字のパスワード、第 2 引数 timeWindowUsed は検証が行われた回数で、RFC によると 1 回だけにすべきということで、カウントして必要に応じて何かするためのもののようです。

第 3 引数は network delay に関係するもののようですが説明を読んでも分かりませんでした。(汗) 参考記事では new VerificationWindow(2, 2) となっていましたが、RFC 推奨は "one time step delay" ということだそうですので GitHub の記事の通りにしておきました。

GenerateAsync メソッド、NotifyAsync メソッドは今回の実装では使わないということで参考記事の通りにしておきました。(これらのメソッドが呼ばれたら異常事態ということで throw NotImplemantationException() として自爆した方が良かったかもしれません)

(4) GoogleAuthenticatorTokenProvider を登録

上のステップ (3) で作成したプロバイダを登録します。 登録すると、フレームワークがプロバイダ��実装されたメソッドを使ってユーザーが入力したパスワードの検証などを行うようです。

App_Start/IdentityConfig.cs ファイルの ApplicationUserManager クラスの Create メソッドに既存のプロバイダ PhoneNumberTokenProvider と EmailTokenProvider を登録するコードがありますので、その下に以下のコードを追加します。

manager.RegisterTwoFactorProvider("GoogleAuthenticator", 
    new GoogleAuthenticatorTokenProvider());

(5) IndexViewModel クラスにプロパティ追加

Models/ManageViewModel.cs ファイルの IndexViewModel クラスに以下のプロパティを追加します。

public class IndexViewModel
{
    public bool HasPassword { get; set; }
    public IList<UserLoginInfo> Logins { get; set; }
    public string PhoneNumber { get; set; }
    public bool TwoFactor { get; set; }
    public bool BrowserRemembered { get; set; }

    // Google Authnticator による 2FA を実装するため追加
    public bool IsGoogleAuthenticatorEnabled { get; set; }
}

さらに、ManageController の Index アクションメソッドに IndexViewModel の IsGoogleAuthenticatorEnabled プロパティを設定するコードを追加します。参考記事には書いてないので注意してください。

var model = new IndexViewModel
{
    HasPassword = HasPassword(),
    PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
    TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
    Logins = await UserManager.GetLoginsAsync(userId),
    BrowserRemembered = await AuthenticationManager
                              .TwoFactorBrowserRememberedAsync(userId),

    // Google Authnticator による 2FA を実装するため追加
    IsGoogleAuthenticatorEnabled = (await UserManager.FindByIdAsync(userId))
                                   .IsGoogleAuthenticatorEnabled
};

(6) 有効化/無効化を操作するコードを View に追加

Views/Manage/Index.cshtml ファイルの下の方(最後の <dl> 要素の直前)に、Google Authenticator の有効化/無効化を切り替えるための以下のコードを追加します。

<dt>Google Authentication:</dt>
<dd>
    @if (Model.IsGoogleAuthenticatorEnabled)
    {
        using (Html.BeginForm("DisableGoogleAuthenticator", "Manage",
            FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
        {
            @Html.AntiForgeryToken()
            <text>有効
                <input type="submit" value="無効化" class="btn btn-link" />
            </text>
        }
    }
    else
    {
        <text>無効
            @Html.ActionLink("有効化", "EnableGoogleAuthenticator")
        </text>
    }
</dd>

(7) GoogleAuthenticatorViewModel クラスを追加

Models/ManageViewModel.cs ファイルに GoogleAuthenticatorViewModel クラスを追加を追加します。参考記事には書いてないので注意してください。

public class GoogleAuthenticatorViewModel
{
    public string SecretKey { get; set; }
    public string BarcodeUrl { get; set; }

    [Required]
    [Display(Name = "コード")]
    public string Code { get; set; }
}

(8) アクションメソッドの追加

Controllers/ManageController.cs の ManageController に、上のステップ (6) で View に追加した submit ボタンと ActionLink の受信先のアクションメソッド EnableGoogleAuthenticator と DisableGoogleAuthenticator を追加します。

using 句に OtpSharp, Base32, System.Text を追加するのを忘れないようにしてください。

//
// GET: /Manage/DisableGoogleAuthenticator
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DisableGoogleAuthenticator()
{
    var user = await UserManager
                     .FindByIdAsync(User.Identity.GetUserId());

    if (user != null)
    {
        user.IsGoogleAuthenticatorEnabled = false;
        user.GoogleAuthenticatorSecretKey = null;
        await UserManager.UpdateAsync(user);
        await SignInManager.SignInAsync(user, 
                                        isPersistent: false, 
                                        rememberBrowser: false);
    }

    return RedirectToAction("Index", "Manage");
}

//
// GET: /Manage/EnableGoogleAuthenticator
public ActionResult EnableGoogleAuthenticator()
{
    byte[] secretKey = KeyGeneration.GenerateRandomKey(20);
    string userName = User.Identity.GetUserName();

    string authenticatorUriFormat = 
        "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6";

    string authnticatorUri = string.Format(
        authenticatorUriFormat,
        HttpUtility.UrlEncode("MVC5TwoFactorAuth"),  // issuer
        HttpUtility.UrlEncode(userName),
        Base32Encoder.Encode(secretKey));

    // QR コードが読めなかった場合の共有キーの表示
    string keyCode = Base32Encoder.Encode(secretKey);
    ViewBag.KeyCode = FormatKey(keyCode);

    var model = new GoogleAuthenticatorViewModel
    {
        SecretKey = keyCode,
        BarcodeUrl = authnticatorUri
    };

    return View(model);
}

//
// POST: /Manage/EnsableGoogleAuthenticator
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EnableGoogleAuthenticator(
                                   GoogleAuthenticatorViewModel model)
{
    if (ModelState.IsValid)
    {
        byte[] secretKey = Base32Encoder.Decode(model.SecretKey);

        long timeWindowUsed = 0;
        var otp = new OtpSharp.Totp(secretKey);
        if (otp.VerifyTotp(model.Code,
                           out timeWindowUsed,
                           new VerificationWindow(previous: 1, future: 1)))
        {
            var user = await UserManager
                             .FindByIdAsync(User.Identity.GetUserId());
            user.IsGoogleAuthenticatorEnabled = true;
            user.GoogleAuthenticatorSecretKey = model.SecretKey;
            await UserManager.UpdateAsync(user);

            return RedirectToAction("Index", "Manage");
        }
        else
        {
            ModelState.AddModelError("Code", "コードが有効ではありません");
        }
    }

    ViewBag.KeyCode = FormatKey(model.SecretKey);
    return View(model);
}

// 共有キーを 4 文字ずつ分けて表示するためのヘルパーメソッド
private string FormatKey(string unformattedKey)
{
    var result = new StringBuilder();
    int currentPosition = 0;
    while (currentPosition + 4 < unformattedKey.Length)
    {
        result.Append(unformattedKey.Substring(currentPosition, 4))
              .Append(" ");
        currentPosition += 4;
    }
    if (currentPosition < unformattedKey.Length)
    {
        result.Append(unformattedKey.Substring(currentPosition));
    }

    return result.ToString().ToLowerInvariant();
}

参考記事のコードから変更・追加を行っています。主な点は以下の通りです。

  1. QR コードが読めない場合に認証アプリに秘密キーを直接入力できるよう、この記事の一番上の画像にあるように秘密キーを表示するようにしました。4 文字ずつ分けて表示しているのは見やすくするためです。4 文字ずつ分けるためのヘルパーメソッド FormatKey を追加しています。
  2. QR コードの生成・表示は Mictosoft のドキュメント「ASP.NET Core での TOTP authenticator アプリの QR コード生成を有効にする」に書いてある qrcode.js を使う方法に変更しました。
  3. VerifyTotp メソッドの第 3 引数は、上のステップ (3) で述べたように、RFC 推奨は "one time step delay" ということだそうですので GitHub の記事の通りにしておきました。

(9) View を追加

上のステップ (8) で追加した EnableGoogleAuthenticator アクションメソッドに対応するビュー EnableGoogleAuthenticator.cshtml を追加しします。

@model MVC5TwoFactorAuth.Models.GoogleAuthenticatorViewModel

@{
    ViewBag.Title = "Google Authenticator の利用";
}

<h2>Google Authenticator の有効化</h2>

<div class="row">
    <div class="col-md-8">
        <h3>1. Google Authenticator による 2 要素認証の有効化</h3>
        <p>スマートフォンの Google Authenticator アプリを起動して右の 
        QR コードをスキャンしてください。</p>
        <h3>2. QR コードをスキャンして得られた 6 桁の数字を入力</h3>
        <p>
            QR コードをスキャンすることにより得られた 
            6 桁の数字を下の[コード]欄に入力し、
            [有効化]ボタンをクリックしてください。
        </p>
        <h3>3. QR コードが読めない場合</h3>
        <p>
            共有キー: <kbd>@ViewBag.KeyCode</kbd> を Google Authenticator 
            アプリに入力して得られた 6 桁の数字を下の[コード]欄に入力し、
            [有効化]ボタンをクリックしてください。
        </p>
        <hr />
        @using (Html.BeginForm("EnableGoogleAuthenticator", 
            "Manage", 
            FormMethod.Post, 
            new { @class = "form-horizontal", role = "form" }))
        {
            @Html.AntiForgeryToken()
            @Html.HiddenFor(m => m.SecretKey)
            @Html.HiddenFor(m => m.BarcodeUrl)
            <div class="form-group">
                @Html.LabelFor(m => m.Code, 
                       new { @class = "col-md-2 control-label" })
                <div class="col-md-10">
                    @Html.TextBoxFor(m => m.Code, 
                                     new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Code, "", 
                                     new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" class="btn btn-primary" 
                           value="有効化" />
                </div>
            </div>
        }
    </div>
    <div class="col-md-4">
        <div id="qrCode"></div>
        <div id="qrCodeData" data-url="@Html.Raw(Model.BarcodeUrl)"></div>
    </div>
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

    <script src="~/Scripts/qrcode.js"></script>
    <script src="~/Scripts/qr.js"></script>
}

上のステップ (8) で述べましたように QR コードの生成・表示は qrcode.js を使う方法に変更しました。

(10) Migration の実施

Visual Studio のパッケージマネージャーコンソールで Add-Migration GoogleAuth, Update-Database を実行します。SQL Server データベースの AspNetUsers テーブルに IsGoogleAuthenticatorEnabled 列と GoogleAuthenticatorSecretKey 列が追加されていることを確認してください。


以上で Google Authenticator を使った 2 要素認証機能は動くようになるはずです。簡単に検証手順を書いておくと:

自分のスマートフォンに Google Authenticator App をインストールします。

MVC5 アプリを実行し、画面右上の[登録]をクリックしてユーザー登録を行ってください。登録に成功すると登録したユーザーでログイン済になるはずです。

画面の右上に「ようこそ・・・」と表示されているはずですが、それをクリックすると以下のように Manage/Index 画面に遷移します。

Manage/Index 画面

まず上の画面の「2 要素認証:」の[有効化]をクリックしてそのユーザーの 2 要素認証を有効にします。その操作で AspNetUsers テーブル の TwoFaxtorEnabled 列が True になります。それをしないと、下の「Google Authenticator」で[有効化]操作を行っても 2 要素認証は働かないので注意してください。

「Google Authenticator」の[有効化]をクリックするとこの記事の一番上の画像の Manage/EnableGoogleAuthenticator 画面に遷移しますので、その画面に書いてある通り、スマートフォンの Google Authenticator App を立ち上げて、QR コードをスキャンするか表示されている共有キーを手入力します。

それによりスマートフォンの Google Authenticator App に 6 桁の数字のパスワードが表示されます。 それを[コード]欄に入力して[有効化]ボタンをクリックすれば MVC5 アプリでそのユーザーの Google Authenticator を使っての 2 要素認証が有効になります。

その後、一旦ログオフしてからログインして 2 要素認証が有効になっているか試します。画面右上の[ログイン]をクリックしてログイン画面で[電子メール]と[パスワード]欄に正しく入力して[ログイン]の欄をクリックすると以下の Account/SendCode 画面に遷移します。

Account/SendCode 画面

そこに表示されているドロップダウンリストにはそのユーザーに対して有効になっている 2 要素認証の項目が表示されます。[GoogleAuthentication]を選択して、[送信]ボタンをクリックすると、以下のように Account/VerifyCode 画面に遷移します。(赤枠の部分は自分が便宜上追加したものでオリジナルのコードには含まれませんので注意))

Account/VerifyCode 画面

スマートフォンの Google Authenticator App を開いてそれに表示されている 6 桁の数字のパスワードを上の画面の[コード]欄に入力して[送信]ボタンをクリックするとログインできます。

Tags: , , , ,

MVC

About this blog

2010年5月にこのブログを立ち上げました。主に ASP.NET Web アプリ関係の記事です。

Calendar

<<  2021年11月  >>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

View posts in large calendar