短信驗(yàn)證碼最佳實(shí)踐

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

2.實(shí)現(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);
????}
}
///?
///?短信驗(yàn)證碼工具類
///?
public?static?class?MsgCaptchaHelper
{
????///?
????///?生成指定位數(shù)的隨機(jī)數(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
///?
///?獲取圖片驗(yàn)證碼
///?
///?"imgCaptchaDto">圖形驗(yàn)證碼請(qǐng)求信息
///?
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;
}
///?
///?獲取圖片驗(yàn)證碼
///?
///?"imgCaptchaDto">圖形驗(yàn)證碼請(qǐng)求信息
[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");
}
///?
///?驗(yàn)證圖片驗(yàn)證碼
///?
///?"imgCaptchaDto">圖形驗(yàn)證碼信息
///?
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;
????}
}
///?
///?驗(yàn)證圖片驗(yàn)證碼
///?
///?"imgCaptchaDto">圖形驗(yàn)證碼信息
///?
[HttpPost("img")]
public?IActionResult?ValidateImageCaptcha(ImgCaptchaDto?imgCaptchaDto)
{
????bool?isCaptchaValid?=?_captchaService.ValidateImageCaptcha(imgCaptchaDto);
????if?(isCaptchaValid)
????{
????????return?Ok("圖形驗(yàn)證碼驗(yàn)證成功");
????}
????else
????{
????????return?StatusCode(StatusCodes.Status403Forbidden,?"驗(yàn)證失敗,請(qǐng)輸入正確手機(jī)號(hào)及獲取到的驗(yàn)證碼");
????}
}
///?
///?獲取短信驗(yàn)證碼
///?
///?"msgCaptchaDto">短信驗(yàn)證碼請(qǐng)求信息
///?
public?(bool,?string)?GetMsgCaptcha(MsgCaptchaDto?msgCaptchaDto)
{
????if?(string.IsNullOrWhiteSpace(msgCaptchaDto.ImgCaptcha))
????{
????????throw?new?BusinessException((int)ErrorCode.BadRequest,?"請(qǐng)輸入圖形驗(yàn)證碼");
????}
????var?cachedImageCaptcha?=?_cache.Get($"ImgCaptcha{msgCaptchaDto.MsgCaptchaType}{msgCaptchaDto.Mobile}");
????if?(!string.Equals(msgCaptchaDto.ImgCaptcha,?cachedImageCaptcha,?StringComparison.OrdinalIgnoreCase))
????{
????????return?(false,?"驗(yàn)證失敗,請(qǐng)輸入正確手機(jī)號(hào)及獲取到的圖形驗(yàn)證碼");
????}
????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,?$"短信驗(yàn)證碼獲取太頻繁,請(qǐng){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實(shí)際發(fā)送短信
????????return?(true,?"發(fā)送成功");
????}
????else????????//非生產(chǎn)環(huán)境,直接將驗(yàn)證碼返給前端,便于調(diào)查跟蹤
????{
????????return?(true,?$"發(fā)送成功,短信驗(yàn)證碼為:{msgCaptcha}");
????}
}
///?
///?驗(yàn)證短信驗(yàn)證碼
///?
///?"msgCaptchaDto">短信驗(yàn)證碼信息
///?
public?(bool,?string)?ValidateMsgCaptcha(MsgCaptchaDto?msgCaptchaDto)
{
????var?key?=?$"MsgCaptcha{msgCaptchaDto.MsgCaptchaType}{msgCaptchaDto.Mobile}";
????var?cachedMsgCaptcha?=?_cache.Get(key);
????if?(cachedMsgCaptcha?==?null)
????{
????????return?(false,?"短信驗(yàn)證碼無效,請(qǐng)重新獲取");
????}
????if?(cachedMsgCaptcha.ValidateCount?>=?3)
????{
????????_cache.Remove(key);
????????return?(false,?"短信驗(yàn)證碼已失效,請(qǐng)重新獲取");
????}
????cachedMsgCaptcha.ValidateCount++;
????if?(!string.Equals(cachedMsgCaptcha.MsgCaptcha,?msgCaptchaDto.MsgCaptcha,?StringComparison.OrdinalIgnoreCase))
????{
????????return?(false,?"短信驗(yàn)證碼錯(cuò)誤");
????}
????else
????{
????????return?(true,?"驗(yàn)證通過");
????}
}
3.運(yùn)行效果:















4.源碼
5.總結(jié)
我們?cè)倩剡^頭來看看騷窩的短信驗(yàn)證碼核心要點(diǎn):

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