短信驗證碼最佳實踐

來源 |?www.cnblogs.com/guokun/p/11042903.html
1、背景 2、實現(xiàn) 3、運行效果: 4、源碼 5、總結
1、背景

2.實現(xiàn)



void?DrawCaptchaCode()
{
????SolidBrush?fontBrush?=?new?SolidBrush(Color.Black);
????int?fontSize?=?GetFontSize(width,?captchaCode.Length);
????Font?font?=?new?Font(FontFamily.GenericSerif,?fontSize,?FontStyle.Bold,?GraphicsUnit.Pixel);
????for?(int?i?=?0;?i?????{
????????fontBrush.Color?=?GetRandomDeepColor();
????????int?shiftPx?=?fontSize?/?6;
????????//float?x?=?i?*?fontSize?+?rand.Next(-shiftPx,?shiftPx)?+?rand.Next(-shiftPx,?shiftPx);
????????float?x?=?i?*?fontSize?+?rand.Next(-shiftPx,?shiftPx)?/?2;
????????//int?maxY?=?height?-?fontSize;
????????int?maxY?=?height?-?fontSize?*?2;
????????if?(maxY?0)
????????{
????????????maxY?=?0;
????????}
????????float?y?=?rand.Next(0,?maxY);
????????graph.DrawString(captchaCode[i].ToString(),?font,?fontBrush,?x,?y);
????}
}????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
?void?DrawDisorderLine()
{
????Pen?linePen?=?new?Pen(new?SolidBrush(Color.Black),?2);
????//for?(int?i?=?0;?i?????for?(int?i?=?0;?i?2;?i++)
????{
????????linePen.Color?=?GetRandomDeepColor();
????????Point?startPoint?=?new?Point(rand.Next(0,?width),?rand.Next(0,?height));
????????Point?endPoint?=?new?Point(rand.Next(0,?width),?rand.Next(0,?height));
????????graph.DrawLine(linePen,?startPoint,?endPoint);
????}
}
///?
///?短信驗證碼工具類
///?
public?static?class?MsgCaptchaHelper
{
????///?
????///?生成指定位數(shù)的隨機數(shù)字碼
????///?
????///?"length">
????///?
????public?static?string?CreateRandomNumber(int?length)
????{
????????Random?random?=?new?Random();
????????StringBuilder?sbMsgCode?=?new?StringBuilder();
????????for?(int?i?=?0;?i?????????{
????????????sbMsgCode.Append(random.Next(0,?9));
????????}
????????return?sbMsgCode.ToString();
????}
}
#region?Private?Fields
private?readonly?IMemoryCache?_cache;
private?readonly?IHostingEnvironment?_hostingEnvironment;
#endregion
#region?Constructors
public?CaptchaService(IMemoryCache?cache,?IHostingEnvironment?hostingEnvironment)
{
????_cache?=?cache;
????_hostingEnvironment?=?hostingEnvironment;
}
#endregion
///?
///?獲取圖片驗證碼
///?
///?"imgCaptchaDto">圖形驗證碼請求信息
///?
public?CaptchaResult?GetImageCaptcha(ImgCaptchaDto?imgCaptchaDto)
{
????var?captchaCode?=?ImageCaptchaHelper.GenerateCaptchaCode();
????var?result?=?ImageCaptchaHelper.GenerateCaptcha(100,?36,?captchaCode);
????_cache.Set($"ImgCaptcha{imgCaptchaDto.ImgCaptchaType}{imgCaptchaDto.Mobile}",?result.CaptchaCode);
????return?result;
}
///?
///?獲取圖片驗證碼
///?
///?"imgCaptchaDto">圖形驗證碼請求信息
[HttpGet("img")]
public?IActionResult?GetImageCaptcha([FromQuery]ImgCaptchaDto?imgCaptchaDto)
{
????var?result?=?_captchaService.GetImageCaptcha(imgCaptchaDto);
????var?stream?=?new?MemoryStream(result.CaptchaByteData);
????return?new?FileStreamResult(stream,?"image/png");
}
///?
///?驗證圖片驗證碼
///?
///?"imgCaptchaDto">圖形驗證碼信息
///?
public?bool?ValidateImageCaptcha(ImgCaptchaDto?imgCaptchaDto)
{
????var?cachedImageCaptcha?=?_cache.Get($"ImgCaptcha{imgCaptchaDto.ImgCaptchaType}{imgCaptchaDto.Mobile}");
????if?(string.Equals(imgCaptchaDto.ImgCaptcha,?cachedImageCaptcha,?StringComparison.OrdinalIgnoreCase))
????{
????????return?true;
????}
????else
????{
????????return?false;
????}
}
///?
///?驗證圖片驗證碼
///?
///?"imgCaptchaDto">圖形驗證碼信息
///?
[HttpPost("img")]
public?IActionResult?ValidateImageCaptcha(ImgCaptchaDto?imgCaptchaDto)
{
????bool?isCaptchaValid?=?_captchaService.ValidateImageCaptcha(imgCaptchaDto);
????if?(isCaptchaValid)
????{
????????return?Ok("圖形驗證碼驗證成功");
????}
????else
????{
????????return?StatusCode(StatusCodes.Status403Forbidden,?"驗證失敗,請輸入正確手機號及獲取到的驗證碼");
????}
}
///?
///?獲取短信驗證碼
///?
///?"msgCaptchaDto">短信驗證碼請求信息
///?
public?(bool,?string)?GetMsgCaptcha(MsgCaptchaDto?msgCaptchaDto)
{
????if?(string.IsNullOrWhiteSpace(msgCaptchaDto.ImgCaptcha))
????{
????????throw?new?BusinessException((int)ErrorCode.BadRequest,?"請輸入圖形驗證碼");
????}
????var?cachedImageCaptcha?=?_cache.Get($"ImgCaptcha{msgCaptchaDto.MsgCaptchaType}{msgCaptchaDto.Mobile}");
????if?(!string.Equals(msgCaptchaDto.ImgCaptcha,?cachedImageCaptcha,?StringComparison.OrdinalIgnoreCase))
????{
????????return?(false,?"驗證失敗,請輸入正確手機號及獲取到的圖形驗證碼");
????}
????string?key?=?$"MsgCaptcha{msgCaptchaDto.MsgCaptchaType}{msgCaptchaDto.Mobile}";
????var?cachedMsgCaptcha?=?_cache.Get(key);
????if?(cachedMsgCaptcha?!=?null)
????{
????????var?offsetSecionds?=?(DateTime.Now?-?cachedMsgCaptcha.CreateTime).Seconds;
????????if?(offsetSecionds?60)
????????{
????????????return?(false,?$"短信驗證碼獲取太頻繁,請{60?-?offsetSecionds}秒之后再獲取");
????????}
????}
????var?msgCaptcha?=?MsgCaptchaHelper.CreateRandomNumber(6);
????msgCaptchaDto.MsgCaptcha?=?msgCaptcha;
????msgCaptchaDto.CreateTime?=?DateTime.Now;
????msgCaptchaDto.ValidateCount?=?0;
????_cache.Set(key,?msgCaptchaDto,?TimeSpan.FromMinutes(2));
????if?(_hostingEnvironment.IsProduction())
????{
????????//TODO:調(diào)用第三方SDK實際發(fā)送短信
????????return?(true,?"發(fā)送成功");
????}
????else????????//非生產(chǎn)環(huán)境,直接將驗證碼返給前端,便于調(diào)查跟蹤
????{
????????return?(true,?$"發(fā)送成功,短信驗證碼為:{msgCaptcha}");
????}
}
///?
///?驗證短信驗證碼
///?
///?"msgCaptchaDto">短信驗證碼信息
///?
public?(bool,?string)?ValidateMsgCaptcha(MsgCaptchaDto?msgCaptchaDto)
{
????var?key?=?$"MsgCaptcha{msgCaptchaDto.MsgCaptchaType}{msgCaptchaDto.Mobile}";
????var?cachedMsgCaptcha?=?_cache.Get(key);
????if?(cachedMsgCaptcha?==?null)
????{
????????return?(false,?"短信驗證碼無效,請重新獲取");
????}
????if?(cachedMsgCaptcha.ValidateCount?>=?3)
????{
????????_cache.Remove(key);
????????return?(false,?"短信驗證碼已失效,請重新獲取");
????}
????cachedMsgCaptcha.ValidateCount++;
????if?(!string.Equals(cachedMsgCaptcha.MsgCaptcha,?msgCaptchaDto.MsgCaptcha,?StringComparison.OrdinalIgnoreCase))
????{
????????return?(false,?"短信驗證碼錯誤");
????}
????else
????{
????????return?(true,?"驗證通過");
????}
}
3.運行效果:















4.源碼
5.總結
我們再回過頭來看看騷窩的短信驗證碼核心要點:

這么多要點中,本方案有兩個沒有實現(xiàn),如截圖所示,同一個手機號在同一時間內(nèi)可以有多個有效的短信驗證碼以及第三方api,第三方api說的并不明確,到底是什么,而且如果是集成第三方了,那么可能就用不上短信驗證碼了,直接用戶名、密碼、第三方api就直接了,至于另一條,同一手機號同一時間內(nèi)可以有多個有效的短信驗證碼,個人感覺不太實用和必要。假如要實踐的話,其實也簡單,方案中短信驗證碼模型中,并不是保存單個短信驗證碼,而是緩存驗證碼列表就OK了,這點不難。
逆鋒起筆是一個專注于程序員圈子的技術平臺,你可以收獲最新技術動態(tài)、最新內(nèi)測資格、BAT等大廠的經(jīng)驗、精品學習資料、職業(yè)路線、副業(yè)思維,微信搜索逆鋒起筆關注!
文章有幫助的話,在看,轉發(fā)吧。 謝謝支持喲 (*^__^*)
評論
圖片
表情
