短信验证码最佳实践
来源 | www.cnblogs.com/guokun/p/11042903.html
1、背景 2、实现 3、运行效果: 4、源码 5、总结
1、背景
2.实现
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 < captchaCode.Length; 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 < rand.Next(3, 5); 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
{
///
/// 生成指定位数的随机数字码
///
/// "length">
///
public static string CreateRandomNumber(int length)
{
Random random = new Random();
StringBuilder sbMsgCode = new StringBuilder();
for (int i = 0; i < length; 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:调用第三方SDK实际发送短信
return (true, "发送成功");
}
else //非生产环境,直接将验证码返给前端,便于调查跟踪
{
return (true, $"发送成功,短信验证码为:{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.总结
我们再回过头来看看骚窝的短信验证码核心要点:
这么多要点中,本方案有两个没有实现,如截图所示,同一个手机号在同一时间内可以有多个有效的短信验证码以及第三方api,第三方api说的并不明确,到底是什么,而且如果是集成第三方了,那么可能就用不上短信验证码了,直接用户名、密码、第三方api就直接了,至于另一条,同一手机号同一时间内可以有多个有效的短信验证码,个人感觉不太实用和必要。假如要实践的话,其实也简单,方案中短信验证码模型中,并不是保存单个短信验证码,而是缓存验证码列表就OK了,这点不难。
逆锋起笔
是一个专注于程序员圈子的技术平台,你可以收获最新技术动态
、最新内测资格
、BAT等大厂的经验
、精品学习资料
、职业路线
、副业思维
,微信搜索逆锋起笔
关注!
文章有帮助的话,在看,转发吧。 谢谢支持哟 (*^__^*)
评论