ASP.NET MVC-Google Authenticator雙因素認證實作

前言

雙因素認證,除了Email及簡訊以外,另一選擇Google Authenticator。本文針對在ASP.NET MVC實作方式作說明。

實作

1.安裝動態密碼及QRCode套件

2.產生動態密碼的私鑰及BarcodeUrl
      private GoogleAuthenticatorModel GenerateGoogleAuthenticatorModel()
        {
            byte[] secretByte = KeyGeneration.GenerateRandomKey(20);
            string userName = "Kimxinfo";
            string barcodeUrl = KeyUrl.GetTotpUrl(secretByte, userName) +  "&issuer=GoogleAuthenticatorLab";
            var model = new GoogleAuthenticatorModel
            {
                SecretKey = Base32Encoder.Encode(secretByte),
                BarcodeUrl = barcodeUrl
            };
            return model;
        }

3.產生Barcode圖檔
  private string GenerateQRCode(GoogleAuthenticatorModel model)
        {
            string fileUrl = $"~/temp/{model.SecretKey}.jpg";
            string filePath = Server.MapPath(fileUrl);
            QRCodeGenerator.ECCLevel eccLevel = QRCodeGenerator.ECCLevel.M;
            using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
            {
                using (QRCodeData qrCodeData =  qrGenerator.CreateQrCode(model.BarcodeUrl, eccLevel))
                {
                    using (QRCode qrCode = new QRCode(qrCodeData))
                    {
                        using (Bitmap image = qrCode.GetGraphic(10, Color.Black,  Color.White, icon: null, iconSizePercent: 0))
                        {
                            using (var stream = new FileStream(filePath,  FileMode.Create))
                            {
                                image.Save(stream,  System.Drawing.Imaging.ImageFormat.Png);
                                return fileUrl;
                            }
                        }
                    }
                }
            }
        }

測試範例
1.手機安裝好Google Authenticator後,掃描以下QrCode或手動輸入私鑰
2. 掃描後,App顯示如下紅框,此6個號碼30秒會切換一次,此組數字就可以用來作驗證。


其它/參考

這個網誌中的熱門文章

[TFS] 分支與合併