diff --git a/src/SimpleAdmin.Api/Auth/AuthRequestDtos.cs b/src/SimpleAdmin.Api/Auth/AuthRequestDtos.cs index 54ed3b0..efe9629 100644 --- a/src/SimpleAdmin.Api/Auth/AuthRequestDtos.cs +++ b/src/SimpleAdmin.Api/Auth/AuthRequestDtos.cs @@ -18,6 +18,37 @@ public class OmsLoginInput public string Password { get; set; } = string.Empty; public OmsLoginType Type { get; set; } = OmsLoginType.User; + + /// 图形验证码 Id(失败达到阈值后必填)。 + public string? CaptchaId { get; set; } + + /// 图形验证码内容(失败达到阈值后必填)。 + public string? CaptchaCode { get; set; } +} + +/// 登录防护状态(是否锁定 / 是否需要验证码)。 +public class OmsLoginGuardOutput +{ + /// 账号是否已临时锁定。 + public bool Locked { get; set; } + + /// 锁定剩余秒数(未锁定为 0)。 + public int LockRemainSeconds { get; set; } + + /// 是否必须携带图形验证码。 + public bool RequireCaptcha { get; set; } + + /// 当前失败次数(窗口内)。 + public int FailCount { get; set; } +} + +/// 图形验证码。 +public class OmsLoginCaptchaOutput +{ + public string CaptchaId { get; set; } = string.Empty; + + /// PNG Base64(不含 data: 前缀)。 + public string ImageBase64 { get; set; } = string.Empty; } public class OmsRefreshTokenInput diff --git a/src/SimpleAdmin.Api/Auth/AuthService.cs b/src/SimpleAdmin.Api/Auth/AuthService.cs index 196f79a..e77fc12 100644 --- a/src/SimpleAdmin.Api/Auth/AuthService.cs +++ b/src/SimpleAdmin.Api/Auth/AuthService.cs @@ -57,23 +57,122 @@ public partial class AuthService( private Guid CurrentUserGuid => CurrentUser.FindClaimValueOrNull(ClaimTypes.NameIdentifier)!.To(); + /// + /// 查询密码登录防护状态(是否锁定 / 是否需要图形验证码)。 + /// + /// 账号。 + /// 登录类型。 + [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 + }; + } + + /// + /// 获取图形验证码(PNG Base64)。失败达到阈值后登录需携带 captchaId + captchaCode。 + /// + [AllowAnonymous] + [HttpGet("/rbac/auth/login-captcha")] + public OmsLoginCaptchaOutput GetLoginCaptcha() + { + var (captchaId, imageBase64) = LoginCaptchaService.Create(); + return new OmsLoginCaptchaOutput + { + CaptchaId = captchaId, + ImageBase64 = imageBase64 + }; + } + /// /// 用户或客户登录。 /// - /// 入参:登录类型、账号和密码。 + /// 入参:登录类型、账号和密码;失败达阈值后需带验证码。 /// 取消令牌。 /// 登录令牌、刷新令牌和用户完整信息(含 menus)。 [AllowAnonymous] [HttpPost("/rbac/auth/login")] public async Task 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(); } /// diff --git a/src/SimpleAdmin.Api/Auth/LoginAbuseGuard.cs b/src/SimpleAdmin.Api/Auth/LoginAbuseGuard.cs new file mode 100644 index 0000000..4d02e01 --- /dev/null +++ b/src/SimpleAdmin.Api/Auth/LoginAbuseGuard.cs @@ -0,0 +1,174 @@ +using Fake.Application; +using Oms.Application.Helpers; + +namespace SimpleAdmin.Api.Auth; + +/// +/// 密码登录防爆破:IP 限流 + 账号失败计数 + 锁定;失败达到阈值后要求图形验证码。 +/// Redis 不可用时放行(避免登录整体不可用),仍依赖密码校验本身。 +/// +public static class LoginAbuseGuard +{ + /// 同一账号连续失败达到该次数后要求验证码。 + public const int CaptchaAfterFails = 2; + + /// 同一账号连续失败达到该次数后锁定。 + 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 异常时放行 + } + } + + /// 锁定剩余秒数;未锁定返回 0。 + 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; + } + } + + /// 记录一次失败;返回最新失败次数。 + 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; + } +} diff --git a/src/SimpleAdmin.Api/Auth/LoginCaptchaService.cs b/src/SimpleAdmin.Api/Auth/LoginCaptchaService.cs new file mode 100644 index 0000000..741be6b --- /dev/null +++ b/src/SimpleAdmin.Api/Auth/LoginCaptchaService.cs @@ -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; + +/// +/// 自建图形验证码(Redis 存答案,一次性消费)。后续可换成腾讯天御 / 阿里云滑动,接口保持 captchaId + code。 +/// +public static class LoginCaptchaService +{ + private const int CaptchaTtlSeconds = 5 * 60; + private const string Alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; + + /// 创建验证码并返回 PNG Base64(不含 data URL 前缀)。 + 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)); + } + + /// 校验并消费验证码;成功返回 true。 + 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(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 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 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); + } + + /// 5x7 点阵字模(数字 + 大写字母子集)。 + private static class Glyphs + { + private static readonly Dictionary Map = Build(); + + public static bool[,] Get(char c) => + Map.TryGetValue(c, out var g) ? g : Map['A']; + + private static Dictionary Build() + { + var raw = new Dictionary + { + ['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(); + 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; + } + } +}