日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > asp.net >内容正文

asp.net

ASP.NET Core 双因素验证2FA 实战经验分享

發(fā)布時(shí)間:2023/12/4 asp.net 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET Core 双因素验证2FA 实战经验分享 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

必讀

本文源碼核心邏輯使用AspNetCore.Totp,為什么不使用AspNetCore.Totp而是使用源碼封裝后面將會(huì)說(shuō)明。

為了防止不提供原網(wǎng)址的轉(zhuǎn)載,特在這里加上原文鏈接:

雙因素認(rèn)證

雙因素身份認(rèn)證就是通過(guò)你所知道再加上你所能擁有的這二個(gè)要素組合到一起才能發(fā)揮作用的身份認(rèn)證系統(tǒng)。雙因素認(rèn)證是一種采用時(shí)間同步技術(shù)的系統(tǒng),采用了基于時(shí)間、事件和密鑰三變量而產(chǎn)生的一次性密碼來(lái)代替?zhèn)鹘y(tǒng)的靜態(tài)密碼。每個(gè)動(dòng)態(tài)密碼卡都有一個(gè)唯一的密鑰,該密鑰同時(shí)存放在服務(wù)器端,每次認(rèn)證時(shí)動(dòng)態(tài)密碼卡與服務(wù)器分別根據(jù)同樣的密鑰,同樣的隨機(jī)參數(shù)(時(shí)間、事件)和同樣的算法計(jì)算了認(rèn)證的動(dòng)態(tài)密碼,從而確保密碼的一致性,從而實(shí)現(xiàn)了用戶的認(rèn)證。就像我們?nèi)ャy行辦卡送的口令牌.

一. 前言

最近公司內(nèi)部SSO登錄一直在找一種安全的方式,目前已實(shí)現(xiàn)方案:賬號(hào)密碼登錄以及手機(jī)驗(yàn)證碼登錄,通過(guò)Apollo切換不同的登錄方式,想起18年看到AspNetCore.Totp并也編寫了DemodotNetCore-2FA登錄,將之前寫的再完善并且在此記錄和分析,希望對(duì)大家有些幫助。

二. AspNetCore.Totp

說(shuō)明一下為什么要用AspNetCore.Totp修改并且重新打包Brook.Totp因AspNetCore.Totp在生成二維碼鏈接時(shí)會(huì)訪問(wèn)404(google.com)網(wǎng)站,國(guó)內(nèi)基本無(wú)法使用,這很不清真,還有就是注入需要注入接口和實(shí)現(xiàn)類,使用起來(lái)很繁瑣,所以才萌生了讓使用起來(lái)更方便,并且不依賴Google生成二維碼的想法

1.生成二維碼

accountIdentity = accountIdentity.Replace(" ", "");var encodedSecretKey = Base32.Encode(accountSecretKey);var provisionUrl = UrlEncoder.Encode(string.Format("otpauth://totp/{0}?secret={1}&issuer={2}", accountIdentity, encodedSecretKey, UrlEncoder.Encode(issuer)));var protocol = useHttps ? "https" : "http";var url = $"{protocol}://chart.googleapis.com/chart?cht=qr&chs={qrCodeWidth}x{qrCodeHeight}&chl={provisionUrl}";var totpSetup = new TotpSetup{QrCodeImage = this.GetQrImage(url),ManualSetupKey = encodedSecretKey};

2.注入方式

  • Startup注入

services.AddSingleton<ITotpSetupGenerator, TotpSetupGenerator>(); services.AddSingleton<ITotpValidator, TotpValidator>(); services.AddSingleton<ITotpGenerator, TotpGenerator>();
  • Controller注入

private readonly ITotpGenerator _totpGenerator;private readonly ITotpSetupGenerator _totpSetupGenerator;private readonly ITotpValidator _totpValidator;public ValuesController(ITotpSetupGenerator totpSetupGenerator){_totpSetupGenerator = totpSetupGenerator;_totpGenerator = new TotpGenerator();_totpValidator = new TotpValidator(_totpGenerator);}

三. Brook.Totp

1.二維碼使用QRCoder來(lái)生成,不依賴外部網(wǎng)絡(luò)

/// <summary>/// 生成二維碼/// </summary>/// <param name="provisionUrl"></param>/// <param name="pixelsPerModule"></param>/// <returns></returns>private string GetQrBase64Imageg(string provisionUrl,int pixelsPerModule){QRCodeGenerator qrGenerator = new QRCodeGenerator();QRCodeData qrCodeData = qrGenerator.CreateQrCode(provisionUrl, QRCodeGenerator.ECCLevel.Q);Base64QRCode qrCode = new Base64QRCode(qrCodeData);string qrCodeImageAsBase64 = qrCode.GetGraphic(2);return $"data:image/png;base64,{qrCodeImageAsBase64}";}

2.注入方式

  • Startup注入

services.AddBrookTotp();
  • Controller注入

private readonly ITotp _totp; public AccountController(ITotp totp) {_totp = totp; }

四.雙因素APP

推薦使用Microsoft Authenticator支持IOS、安卓可自動(dòng)備份

五. 完整流程效果圖

使用Microsoft Authenticator

  • 正常登錄

  • 登錄成功后綁定,使用Microsoft Authenticator掃描二維碼,然后輸入顯示的6位數(shù)字驗(yàn)證碼

  • 綁定后再次登錄

  • 六.如何使用

    所有源代碼請(qǐng)參照我的GitHub?https://github.com/yuefengkai/Brook.Totp

  • EF Core In Memory Database所有的數(shù)據(jù)只存在內(nèi)存中

  • Cache in-memory

  • dotNET Core Authentication

  • 下方只展示部分代碼

    1.新建netCoreMVC項(xiàng)目添加Nuget包Brook.Totp

    2.注入方式

    • Startup注入

    services.AddMemoryCache(); services.AddSingleton<ICacheManage, CacheManage>(); services.AddBrookTotp(); services.AddDbContext<BrookTotpDBContext>(options => options.UseInMemoryDatabase(databaseName: "BrookTotpDB"));
    • Controller使用

    private readonly ITotp _totp; public AccountController(ITotp totp) {_totp = totp; } //獲取二維碼 [Authorize] public IActionResult GetQr() {var totpSetup = _totp.GenerateUrl("dotNETBuild", CurremtUser.Email, CurremtUser.SecretKeyFor2FA);return Json(new { qrCodeContennt = totpSetup.QrCodeImageContent }); } //驗(yàn)證雙因素校驗(yàn)碼 [Authorize] [HttpPost] public async Task<IActionResult> Valid(int code) {var valid = _totp.Validate(CurremtUser.SecretKeyFor2FA, code, 30);if (!valid){return Json(new { result = 0, msg = "2FA校驗(yàn)失敗" });}//校驗(yàn)成功后 如果是第一次綁定校驗(yàn) 需將用戶的accountSecretKey 存入數(shù)據(jù)庫(kù)CurremtUser.IsOpen2FA = true;await _userService.UpdateAsync(CurremtUser);_cacheManage.Remove(string.Format(CacheKeys.GetUserForEmail, CurremtUser.Email));var claims = new List<Claim>{new Claim("user", CurremtUser.Email),new Claim("role", "Member")};await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies", "user", "role")));return Json(new { result = 1, msg = "2FA校驗(yàn)成功", url = "/Home/Index" }); }

    七.寫在最后

    以上所有源代碼已開源在?https://github.com/yuefengkai/Brook.Totp

    作者:Brook

    總結(jié)

    以上是生活随笔為你收集整理的ASP.NET Core 双因素验证2FA 实战经验分享的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。