feat: 密码登录增加 IP 限流、失败锁定与图形验证码
Some checks failed
Build and Deploy / deploy (push) Has been cancelled

降低账号密码撞库与爆破风险,失败达阈值后再要求验证码。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zzh 2026-11-14 19:26:50 +08:00
parent 0e68f7a87e
commit 91d5aa1725
4 changed files with 552 additions and 7 deletions

View File

@ -18,6 +18,37 @@ public class OmsLoginInput
public string Password { get; set; } = string.Empty;
public OmsLoginType Type { get; set; } = OmsLoginType.User;
/// <summary>图形验证码 Id(失败达到阈值后必填)。</summary>
public string? CaptchaId { get; set; }
/// <summary>图形验证码内容(失败达到阈值后必填)。</summary>
public string? CaptchaCode { get; set; }
}
/// <summary>登录防护状态(是否锁定 / 是否需要验证码)。</summary>
public class OmsLoginGuardOutput
{
/// <summary>账号是否已临时锁定。</summary>
public bool Locked { get; set; }
/// <summary>锁定剩余秒数(未锁定为 0)。</summary>
public int LockRemainSeconds { get; set; }
/// <summary>是否必须携带图形验证码。</summary>
public bool RequireCaptcha { get; set; }
/// <summary>当前失败次数(窗口内)。</summary>
public int FailCount { get; set; }
}
/// <summary>图形验证码。</summary>
public class OmsLoginCaptchaOutput
{
public string CaptchaId { get; set; } = string.Empty;
/// <summary>PNG Base64(不含 data: 前缀)。</summary>
public string ImageBase64 { get; set; } = string.Empty;
}
public class OmsRefreshTokenInput

View File

@ -57,23 +57,122 @@ public partial class AuthService(
private Guid CurrentUserGuid => CurrentUser.FindClaimValueOrNull(ClaimTypes.NameIdentifier)!.To<Guid>();
/// <summary>
/// 查询密码登录防护状态(是否锁定 / 是否需要图形验证码)。
/// </summary>
/// <param name="account">账号。</param>
/// <param name="type">登录类型。</param>
[AllowAnonymous]
[HttpGet("/rbac/auth/login-guard")]
public OmsLoginGuardOutput GetLoginGuard(
[FromQuery] string account,
[FromQuery] OmsLoginType type = OmsLoginType.User)
{
var normalized = LoginAbuseGuard.NormalizeAccount(account);
if (string.IsNullOrEmpty(normalized))
{
return new OmsLoginGuardOutput();
}
var failCount = LoginAbuseGuard.GetFailCount(type, normalized);
var lockRemain = LoginAbuseGuard.GetLockRemainSeconds(type, normalized);
return new OmsLoginGuardOutput
{
FailCount = failCount,
Locked = lockRemain > 0,
LockRemainSeconds = lockRemain,
RequireCaptcha = lockRemain <= 0 && failCount >= LoginAbuseGuard.CaptchaAfterFails
};
}
/// <summary>
/// 获取图形验证码(PNG Base64)。失败达到阈值后登录需携带 captchaId + captchaCode。
/// </summary>
[AllowAnonymous]
[HttpGet("/rbac/auth/login-captcha")]
public OmsLoginCaptchaOutput GetLoginCaptcha()
{
var (captchaId, imageBase64) = LoginCaptchaService.Create();
return new OmsLoginCaptchaOutput
{
CaptchaId = captchaId,
ImageBase64 = imageBase64
};
}
/// <summary>
/// 用户或客户登录。
/// </summary>
/// <param name="input">入参:登录类型、账号和密码。</param>
/// <param name="input">入参:登录类型、账号和密码;失败达阈值后需带验证码。</param>
/// <param name="cancellationToken">取消令牌。</param>
/// <returns>登录令牌、刷新令牌和用户完整信息(含 menus)。</returns>
[AllowAnonymous]
[HttpPost("/rbac/auth/login")]
public async Task<OmsLoginResultDto> LoginAsync([FromBody] OmsLoginInput input, CancellationToken cancellationToken = default)
{
return input.Type switch
var accountRaw = (input.Account ?? string.Empty).Trim();
var accountKey = LoginAbuseGuard.NormalizeAccount(accountRaw);
if (string.IsNullOrEmpty(accountKey) || string.IsNullOrWhiteSpace(input.Password))
{
OmsLoginType.User => await LoginAdminAsync(input.Account, input.Password, cancellationToken),
OmsLoginType.Customer => await LoginCustomerAsync(input.Account, input.Password, cancellationToken),
OmsLoginType.Agent => await LoginAgentAsync(input.Account, input.Password, cancellationToken),
_ => throw new BusinessException("不支持的登录类型")
};
throw new BusinessException("账号或密码错误");
}
var ip = ResolveClientIp();
LoginAbuseGuard.EnsureIpAllowed(ip);
LoginAbuseGuard.EnsureNotLocked(input.Type, accountKey);
if (LoginAbuseGuard.RequiresCaptcha(input.Type, accountKey))
{
if (!LoginCaptchaService.VerifyAndConsume(input.CaptchaId, input.CaptchaCode))
{
throw new BusinessException("请完成图形验证后重试");
}
}
try
{
var result = input.Type switch
{
OmsLoginType.User => await LoginAdminAsync(accountRaw, input.Password, cancellationToken),
OmsLoginType.Customer => await LoginCustomerAsync(accountRaw, input.Password, cancellationToken),
OmsLoginType.Agent => await LoginAgentAsync(accountRaw, input.Password, cancellationToken),
_ => throw new BusinessException("不支持的登录类型")
};
LoginAbuseGuard.ClearFailures(input.Type, accountKey);
return result;
}
catch (BusinessException ex)
{
// 凭证类失败计入防爆破;业务状态(停用等)也计入,避免被用来探测
var fails = LoginAbuseGuard.RecordFailure(input.Type, accountKey);
if (fails >= LoginAbuseGuard.LockAfterFails)
{
throw new BusinessException($"尝试次数过多,请 {LoginAbuseGuard.LockSeconds / 60} 分钟后再试");
}
if (fails >= LoginAbuseGuard.CaptchaAfterFails)
{
throw new BusinessException($"{ex.Message},请完成图形验证后重试");
}
throw;
}
}
private string? ResolveClientIp()
{
var http = httpContextAccessor.HttpContext;
if (http == null) return null;
var forwarded = http.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (!string.IsNullOrWhiteSpace(forwarded))
{
var first = forwarded.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(first)) return first;
}
return http.Connection.RemoteIpAddress?.ToString();
}
/// <summary>

View File

@ -0,0 +1,174 @@
using Fake.Application;
using Oms.Application.Helpers;
namespace SimpleAdmin.Api.Auth;
/// <summary>
/// 密码登录防爆破:IP 限流 + 账号失败计数 + 锁定;失败达到阈值后要求图形验证码。
/// Redis 不可用时放行(避免登录整体不可用),仍依赖密码校验本身。
/// </summary>
public static class LoginAbuseGuard
{
/// <summary>同一账号连续失败达到该次数后要求验证码。</summary>
public const int CaptchaAfterFails = 2;
/// <summary>同一账号连续失败达到该次数后锁定。</summary>
public const int LockAfterFails = 5;
public const int LockSeconds = 15 * 60;
public const int FailWindowSeconds = 30 * 60;
public const int IpMaxPerMinute = 30;
public const int IpMaxPerHour = 120;
public static void EnsureIpAllowed(string? ip)
{
var ipKey = NormalizeIp(ip);
TryIncr($"oms:login:ip:rpm:{ipKey}:{DateTime.UtcNow:yyyyMMddHHmm}", IpMaxPerMinute, 70,
"登录过于频繁,请稍后再试");
TryIncr($"oms:login:ip:rph:{ipKey}:{DateTime.UtcNow:yyyyMMddHH}", IpMaxPerHour, 3700,
"登录过于频繁,请稍后再试");
}
public static void EnsureNotLocked(OmsLoginType loginType, string account)
{
try
{
var ttl = GetLockRemainSeconds(loginType, account);
if (ttl > 0)
{
var minutes = Math.Max(1, (int)Math.Ceiling(ttl / 60.0));
throw new BusinessException($"尝试次数过多,请 {minutes} 分钟后再试");
}
}
catch (BusinessException)
{
throw;
}
catch
{
// Redis 异常时放行
}
}
/// <summary>锁定剩余秒数;未锁定返回 0。</summary>
public static int GetLockRemainSeconds(OmsLoginType loginType, string account)
{
try
{
var ttl = RedisHelper.Client.Ttl(LockRedisKey(loginType, account));
return ttl > 0 ? (int)ttl : 0;
}
catch
{
return 0;
}
}
public static bool RequiresCaptcha(OmsLoginType loginType, string account)
{
return GetFailCount(loginType, account) >= CaptchaAfterFails;
}
public static int GetFailCount(OmsLoginType loginType, string account)
{
var key = AccountKey(loginType, account);
try
{
var raw = RedisHelper.Client.Get($"oms:login:fail:{key}");
return int.TryParse(raw, out var n) ? n : 0;
}
catch
{
return 0;
}
}
/// <summary>记录一次失败;返回最新失败次数。</summary>
public static int RecordFailure(OmsLoginType loginType, string account)
{
var key = AccountKey(loginType, account);
try
{
var client = RedisHelper.Client;
var failKey = $"oms:login:fail:{key}";
var next = (int)client.Incr(failKey);
if (next == 1)
{
client.Expire(failKey, FailWindowSeconds);
}
if (next >= LockAfterFails)
{
client.Set(LockRedisKey(loginType, account), "1", LockSeconds);
client.Del(failKey);
}
return next;
}
catch
{
return 0;
}
}
public static void ClearFailures(OmsLoginType loginType, string account)
{
var key = AccountKey(loginType, account);
try
{
var client = RedisHelper.Client;
client.Del($"oms:login:fail:{key}");
client.Del(LockRedisKey(loginType, account));
}
catch
{
// ignore
}
}
private static string LockRedisKey(OmsLoginType loginType, string account) =>
$"oms:login:lock:{AccountKey(loginType, account)}";
private static void TryIncr(string redisKey, int max, int ttlSeconds, string denyMessage)
{
try
{
var client = RedisHelper.Client;
var next = client.Incr(redisKey);
if (next == 1)
{
client.Expire(redisKey, ttlSeconds);
}
if (next > max)
{
throw new BusinessException(denyMessage);
}
}
catch (BusinessException)
{
throw;
}
catch
{
// Redis 不可用时放行
}
}
private static string AccountKey(OmsLoginType loginType, string account)
{
var raw = $"{(int)loginType}:{NormalizeAccount(account)}";
return raw.Length > 96 ? raw[..96] : raw;
}
public static string NormalizeAccount(string? account)
{
return (account ?? string.Empty).Trim().ToLowerInvariant();
}
public static string NormalizeIp(string? ip)
{
var raw = string.IsNullOrWhiteSpace(ip) ? "unknown" : ip.Trim();
return raw.Length > 64 ? raw[..64] : raw;
}
}

View File

@ -0,0 +1,241 @@
using System.Security.Cryptography;
using Oms.Application.Helpers;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
namespace SimpleAdmin.Api.Auth;
/// <summary>
/// 自建图形验证码(Redis 存答案,一次性消费)。后续可换成腾讯天御 / 阿里云滑动,接口保持 captchaId + code。
/// </summary>
public static class LoginCaptchaService
{
private const int CaptchaTtlSeconds = 5 * 60;
private const string Alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
/// <summary>创建验证码并返回 PNG Base64(不含 data URL 前缀)。</summary>
public static (string CaptchaId, string ImageBase64) Create()
{
var code = RandomCode(4);
var captchaId = Guid.NewGuid().ToString("N");
try
{
RedisHelper.Client.Set(BuildKey(captchaId), code, CaptchaTtlSeconds);
}
catch
{
// Redis 不可用时仍返回图,校验阶段会失败并提示稍后重试
}
var png = RenderPng(code);
return (captchaId, Convert.ToBase64String(png));
}
/// <summary>校验并消费验证码;成功返回 true。</summary>
public static bool VerifyAndConsume(string? captchaId, string? captchaCode)
{
if (string.IsNullOrWhiteSpace(captchaId) || string.IsNullOrWhiteSpace(captchaCode))
{
return false;
}
var id = captchaId.Trim();
var code = captchaCode.Trim().ToUpperInvariant();
if (id.Length is < 8 or > 64 || code.Length is < 3 or > 8)
{
return false;
}
try
{
var key = BuildKey(id);
var expected = RedisHelper.Client.Get(key);
RedisHelper.Client.Del(key);
return !string.IsNullOrEmpty(expected)
&& string.Equals(expected, code, StringComparison.OrdinalIgnoreCase);
}
catch
{
return false;
}
}
private static string BuildKey(string captchaId) => $"oms:login:captcha:{captchaId}";
private static string RandomCode(int length)
{
var chars = new char[length];
for (var i = 0; i < length; i++)
{
chars[i] = Alphabet[RandomNumberGenerator.GetInt32(Alphabet.Length)];
}
return new string(chars);
}
private static byte[] RenderPng(string code)
{
const int width = 120;
const int height = 40;
using var image = new Image<Rgba32>(width, height);
image.Mutate(ctx => ctx.BackgroundColor(new Rgba32(248, 250, 252)));
// 干扰线
for (var i = 0; i < 5; i++)
{
var c = RandomGray(160, 210);
var x0 = Next(0, width);
var y0 = Next(0, height);
var x1 = Next(0, width);
var y1 = Next(0, height);
DrawLine(image, x0, y0, x1, y1, c);
}
// 噪点
for (var i = 0; i < 80; i++)
{
image[Next(0, width), Next(0, height)] = RandomGray(140, 220);
}
var startX = 12;
for (var i = 0; i < code.Length; i++)
{
var glyph = Glyphs.Get(code[i]);
var ox = startX + i * 26 + Next(-1, 2);
var oy = 8 + Next(-2, 3);
DrawGlyph(image, glyph, ox, oy, new Rgba32(29, 33, 41));
}
using var ms = new MemoryStream();
image.Save(ms, new PngEncoder());
return ms.ToArray();
}
private static void DrawGlyph(Image<Rgba32> image, bool[,] glyph, int ox, int oy, Rgba32 color)
{
var rows = glyph.GetLength(0);
var cols = glyph.GetLength(1);
for (var y = 0; y < rows; y++)
{
for (var x = 0; x < cols; x++)
{
if (!glyph[y, x]) continue;
// 2x 放大
for (var dy = 0; dy < 2; dy++)
for (var dx = 0; dx < 2; dx++)
{
var px = ox + x * 2 + dx;
var py = oy + y * 2 + dy;
if ((uint)px < (uint)image.Width && (uint)py < (uint)image.Height)
{
image[px, py] = color;
}
}
}
}
}
private static void DrawLine(Image<Rgba32> image, int x0, int y0, int x1, int y1, Rgba32 color)
{
var dx = Math.Abs(x1 - x0);
var dy = Math.Abs(y1 - y0);
var sx = x0 < x1 ? 1 : -1;
var sy = y0 < y1 ? 1 : -1;
var err = dx - dy;
while (true)
{
if ((uint)x0 < (uint)image.Width && (uint)y0 < (uint)image.Height)
{
image[x0, y0] = color;
}
if (x0 == x1 && y0 == y1) break;
var e2 = 2 * err;
if (e2 > -dy)
{
err -= dy;
x0 += sx;
}
if (e2 < dx)
{
err += dx;
y0 += sy;
}
}
}
private static Rgba32 RandomGray(int min, int max)
{
var v = (byte)Next(min, max + 1);
return new Rgba32(v, v, v);
}
private static int Next(int minInclusive, int maxExclusive)
{
if (maxExclusive <= minInclusive) return minInclusive;
return RandomNumberGenerator.GetInt32(minInclusive, maxExclusive);
}
/// <summary>5x7 点阵字模(数字 + 大写字母子集)。</summary>
private static class Glyphs
{
private static readonly Dictionary<char, bool[,]> Map = Build();
public static bool[,] Get(char c) =>
Map.TryGetValue(c, out var g) ? g : Map['A'];
private static Dictionary<char, bool[,]> Build()
{
var raw = new Dictionary<char, string[]>
{
['2'] = ["11110", "00001", "00010", "00100", "01000", "10000", "11111"],
['3'] = ["11110", "00001", "00001", "01110", "00001", "00001", "11110"],
['4'] = ["00010", "00110", "01010", "10010", "11111", "00010", "00010"],
['5'] = ["11111", "10000", "11110", "00001", "00001", "00001", "11110"],
['6'] = ["01110", "10000", "10000", "11110", "10001", "10001", "01110"],
['7'] = ["11111", "00001", "00010", "00100", "01000", "01000", "01000"],
['8'] = ["01110", "10001", "10001", "01110", "10001", "10001", "01110"],
['9'] = ["01110", "10001", "10001", "01111", "00001", "00001", "01110"],
['A'] = ["01110", "10001", "10001", "11111", "10001", "10001", "10001"],
['B'] = ["11110", "10001", "10001", "11110", "10001", "10001", "11110"],
['C'] = ["01110", "10001", "10000", "10000", "10000", "10001", "01110"],
['D'] = ["11110", "10001", "10001", "10001", "10001", "10001", "11110"],
['E'] = ["11111", "10000", "10000", "11110", "10000", "10000", "11111"],
['F'] = ["11111", "10000", "10000", "11110", "10000", "10000", "10000"],
['G'] = ["01110", "10001", "10000", "10111", "10001", "10001", "01110"],
['H'] = ["10001", "10001", "10001", "11111", "10001", "10001", "10001"],
['J'] = ["00111", "00001", "00001", "00001", "00001", "10001", "01110"],
['K'] = ["10001", "10010", "10100", "11000", "10100", "10010", "10001"],
['L'] = ["10000", "10000", "10000", "10000", "10000", "10000", "11111"],
['M'] = ["10001", "11011", "10101", "10001", "10001", "10001", "10001"],
['N'] = ["10001", "11001", "10101", "10011", "10001", "10001", "10001"],
['P'] = ["11110", "10001", "10001", "11110", "10000", "10000", "10000"],
['Q'] = ["01110", "10001", "10001", "10001", "10101", "10010", "01101"],
['R'] = ["11110", "10001", "10001", "11110", "10100", "10010", "10001"],
['S'] = ["01111", "10000", "10000", "01110", "00001", "00001", "11110"],
['T'] = ["11111", "00100", "00100", "00100", "00100", "00100", "00100"],
['U'] = ["10001", "10001", "10001", "10001", "10001", "10001", "01110"],
['V'] = ["10001", "10001", "10001", "10001", "10001", "01010", "00100"],
['W'] = ["10001", "10001", "10001", "10001", "10101", "11011", "10001"],
['X'] = ["10001", "10001", "01010", "00100", "01010", "10001", "10001"],
['Y'] = ["10001", "10001", "01010", "00100", "00100", "00100", "00100"],
['Z'] = ["11111", "00001", "00010", "00100", "01000", "10000", "11111"],
};
var map = new Dictionary<char, bool[,]>();
foreach (var (ch, rows) in raw)
{
var g = new bool[7, 5];
for (var y = 0; y < 7; y++)
for (var x = 0; x < 5; x++)
g[y, x] = rows[y][x] == '1';
map[ch] = g;
}
return map;
}
}
}