.NETCORE 开发登录接口MFA谷歌多因子身份验证

1.maf帮助类

cs 复制代码
 public class GoogleAuthenticator
    {
        private readonly static DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        private TimeSpan DefaultClockDriftTolerance { get; set; }

        public GoogleAuthenticator()
        {
            DefaultClockDriftTolerance = TimeSpan.FromSeconds(30);
        }

        /// <summary>
        /// Generate a setup code for a Google Authenticator user to scan
        /// </summary>
        /// <param name="issuer">Issuer ID (the name of the system, i.e. 'MyApp'), can be omitted but not recommended https://github.com/google/google-authenticator/wiki/Key-Uri-Format </param>
        /// <param name="accountTitleNoSpaces">Account Title (no spaces)</param>
        /// <param name="accountSecretKey">Account Secret Key</param>
        /// <param name="QRPixelsPerModule">Number of pixels per QR Module (2 pixels give ~ 100x100px QRCode)</param>
        /// <returns>SetupCode object</returns>
        public SetupCode GenerateSetupCode(string issuer, string accountTitleNoSpaces, string accountSecretKey, int QRPixelsPerModule)
        {
            byte[] key = Encoding.UTF8.GetBytes(accountSecretKey);
            return GenerateSetupCode(issuer, accountTitleNoSpaces, key, QRPixelsPerModule);
        }

        /// <summary>
        /// Generate a setup code for a Google Authenticator user to scan
        /// </summary>
        /// <param name="issuer">Issuer ID (the name of the system, i.e. 'MyApp'), can be omitted but not recommended https://github.com/google/google-authenticator/wiki/Key-Uri-Format </param>
        /// <param name="accountTitleNoSpaces">Account Title (no spaces)</param>
        /// <param name="accountSecretKey">Account Secret Key as byte[]</param>
        /// <param name="QRPixelsPerModule">Number of pixels per QR Module (2 = ~120x120px QRCode)</param>
        /// <returns>SetupCode object</returns>
        public SetupCode GenerateSetupCode(string issuer, string accountTitleNoSpaces, byte[] accountSecretKey, int QRPixelsPerModule)
        {
            if (accountTitleNoSpaces == null) { throw new NullReferenceException("Account Title is null"); }
            accountTitleNoSpaces = RemoveWhitespace(accountTitleNoSpaces);
            string encodedSecretKey = Base32Encoding.ToString(accountSecretKey);
            string provisionUrl = null;
            provisionUrl = String.Format("otpauth://totp/{2}:{0}?secret={1}&issuer={2}", accountTitleNoSpaces, encodedSecretKey.Replace("=", ""), UrlEncode(issuer));



            using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
            using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(provisionUrl, QRCodeGenerator.ECCLevel.M))
            using (QRCode qrCode = new QRCode(qrCodeData))
            using (Bitmap qrCodeImage = qrCode.GetGraphic(QRPixelsPerModule))
            using (MemoryStream ms = new MemoryStream())
            {
                qrCodeImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                return new SetupCode(accountTitleNoSpaces, encodedSecretKey, String.Format("data:image/png;base64,{0}", Convert.ToBase64String(ms.ToArray())));
            }

        }

        private static string RemoveWhitespace(string str)
        {
            return new string(str.Where(c => !Char.IsWhiteSpace(c)).ToArray());
        }

        private string UrlEncode(string value)
        {
            StringBuilder result = new StringBuilder();
            string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";

            foreach (char symbol in value)
            {
                if (validChars.IndexOf(symbol) != -1)
                {
                    result.Append(symbol);
                }
                else
                {
                    result.Append('%' + String.Format("{0:X2}", (int)symbol));
                }
            }

            return result.ToString().Replace(" ", "%20");
        }

        public string GeneratePINAtInterval(string accountSecretKey, long counter, int digits = 6)
        {
            return GenerateHashedCode(accountSecretKey, counter, digits);
        }

        internal string GenerateHashedCode(string secret, long iterationNumber, int digits = 6)
        {
            byte[] key = Encoding.UTF8.GetBytes(secret);
            return GenerateHashedCode(key, iterationNumber, digits);
        }

        internal string GenerateHashedCode(byte[] key, long iterationNumber, int digits = 6)
        {
            byte[] counter = BitConverter.GetBytes(iterationNumber);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(counter);
            }

            HMACSHA1 hmac = new HMACSHA1(key);

            byte[] hash = hmac.ComputeHash(counter);

            int offset = hash[hash.Length - 1] & 0xf;

            // Convert the 4 bytes into an integer, ignoring the sign.
            int binary =
              ((hash[offset] & 0x7f) << 24)
              | (hash[offset + 1] << 16)
              | (hash[offset + 2] << 8)
              | (hash[offset + 3]);

            int password = binary % (int)Math.Pow(10, digits);
            return password.ToString(new string('0', digits));
        }

        private long GetCurrentCounter()
        {
            return GetCurrentCounter(DateTime.UtcNow, _epoch, 30);
        }

        private long GetCurrentCounter(DateTime now, DateTime epoch, int timeStep)
        {
            return (long)(now - epoch).TotalSeconds / timeStep;
        }

        public bool ValidateTwoFactorPIN(string accountSecretKey, string twoFactorCodeFromClient)
        {
            return ValidateTwoFactorPIN(accountSecretKey, twoFactorCodeFromClient, DefaultClockDriftTolerance);
        }

        public bool ValidateTwoFactorPIN(string accountSecretKey, string twoFactorCodeFromClient, TimeSpan timeTolerance)
        {
            var codes = GetCurrentPINs(accountSecretKey, timeTolerance);
            return codes.Any(c => c == twoFactorCodeFromClient);
        }

        public string[] GetCurrentPINs(string accountSecretKey, TimeSpan timeTolerance)
        {
            List<string> codes = new List<string>();
            long iterationCounter = GetCurrentCounter();
            int iterationOffset = 0;

            if (timeTolerance.TotalSeconds > 30)
            {
                iterationOffset = Convert.ToInt32(timeTolerance.TotalSeconds / 30.00);
            }

            long iterationStart = iterationCounter - iterationOffset;
            long iterationEnd = iterationCounter + iterationOffset;

            for (long counter = iterationStart; counter <= iterationEnd; counter++)
            {
                codes.Add(GeneratePINAtInterval(accountSecretKey, counter));
            }

            return codes.ToArray();
        }
    }

2.nugget安装GoogleAuthenticator;

开启mfa时候请求以下接口

cs 复制代码
 public async Task<ActionResult<Result>> GoogleImg()
        {
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                var UserId = HttpContext.Session.GetString("UserId");
                if (UserId != "")
                {

                    var userinfo = _userAirware.Query(u => u.UserId == Convert.ToInt32(UserId)).Result.FirstOrDefault();
                    if (userinfo != null)
                    {
                        if (userinfo.IsSuccess == 0)
                        {
                            GoogleAuthenticator tfa = new GoogleAuthenticator();
                            var guid = Guid.NewGuid().ToString();
                            SetupCode setupInfo = tfa.GenerateSetupCode("FS Airware", userinfo.UserEmail, guid, 3);
                            //更新guid到当前登录用户
                            userinfo.GoogleAuthkey = guid;
                            await ???.Update(userinfo);
                            QRImageUrl = setupInfo.QrCodeSetupImageUrl;
                            ManualEntryKey = setupInfo.ManualEntryKey;
                            //dic.Add("isverify", "true");
                            dic.Add("img", QRImageUrl);
                            return ApiResultHelper.renderSuccess(dic, "Login succeeded");
                        }
                        return ApiResultHelper.renderError("ENABLED");
                    }
                }

                return ApiResultHelper.renderError("非法请求!");
            }
            catch (Exception e)
            {
                return ApiResultHelper.renderError();
            }
        }

4.验证接口

cs 复制代码
 public async Task<ActionResult<Result>> GoogleVerify(string checkcode)
        {
            var UserId = HttpContext.Session.GetString("UserId");
            Dictionary<string, string> dic1 = new Dictionary<string, string>();
            //判断当前用户是否登录成功
            if (UserId != "")
            {
                var userinfo = _userAirware.Query(u => u.UserId == Convert.ToInt32(UserId)).Result.FirstOrDefault();
                if (userinfo != null)
                {
                    if (userinfo.IsVerify == 0)
                    {
                        GoogleAuthenticator gat = new GoogleAuthenticator();
                        var result = gat.ValidateTwoFactorPIN(userinfo.GoogleAuthkey, checkcode);
                        if (result)
                        {
                            Dictionary<string, string> clims = new Dictionary<string, string>
                            {
                                {"ProjectName",userinfo.UserFirstName }
                            };
                            await ???.Update(userinfo);
                            string token = _jwt.GetToken(clims);
                            dic1.Add("isverify", "true");
                            dic1.Add("token", token);
                            dic1.Add("userid", userinfo.UserId + "");
                            dic1.Add("name", userinfo.UserFirstName);
                            return ApiResultHelper.renderSuccess(dic1);
                        }
                        else
                        {
                            return ApiResultHelper.renderError(false);
                        }
                    }
                }
            }
            return ApiResultHelper.renderError("非法访问!");
        }
相关推荐
时光追逐者16 小时前
WaterCloud:一套基于.NET 8.0 + LayUI的快速开发框架,完全开源免费!
前端·microsoft·开源·c#·.net·layui·.netcore
@Unity打怪升级1 天前
【C#】CacheManager:高效的 .NET 缓存管理库
开发语言·后端·机器学习·缓存·c#·.net·.netcore
csdn_aspnet1 天前
.NET Core 高性能并发编程
.netcore
三天不学习1 天前
.NET Core 集成 MiniProfiler性能分析工具
.netcore
AitTech1 天前
构建.NET Core Web API为Windows服务安装包
windows·.netcore
yufei-coder2 天前
掌握 C# 文件和输入输出操作
windows·c#·.netcore·visual studio
友恒3 天前
C#单元测试(一):用 NUnit 和 .NET Core 进行单元测试
单元测试·c#·.netcore
湛江小浪石(峰)4 天前
.NetCore 8 SwaggerGen 显示接口注析
.netcore
csdn_aspnet6 天前
ASP.NET Core 创建使用异步队列
.netcore·async·异步
时光追逐者8 天前
C#/.NET/.NET Core技术前沿周刊 | 第 6 期(2024年9.16-9.22)
开发语言·microsoft·架构·c#·.net·.netcore·周刊