Add WmsLite monorepo with JWT auth, tenant context, and project READMEs.
Implement API security baseline (sys_user, JWT, audit fields, transactions, unique constraints) and Web real login with 401 handling. Document setup and development workflows in root, WmsLite.Api, and WmsLite.Web README files. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
commit
fa1b286463
241 files changed
+31188
No files matched your search
@@ -0,0 +1,61 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WmsLite.Api.Infrastructure.HttpLogging;
|
||||
|
||||
internal static class HttpAccessLogFormatter
|
||||
{
|
||||
private const string Bar = "────────────────────────────────────────";
|
||||
private const string Thick = "════════════════════════════════════════";
|
||||
|
||||
public static string Build(
|
||||
string method,
|
||||
string? path,
|
||||
int statusCode,
|
||||
string requestContent,
|
||||
string responseContent,
|
||||
IReadOnlyList<string> sqlStatements)
|
||||
{
|
||||
var sb = new StringBuilder(512 + requestContent.Length + responseContent.Length);
|
||||
sb.AppendLine(Thick);
|
||||
sb.AppendLine(" HTTP ACCESS");
|
||||
sb.AppendLine(Thick);
|
||||
sb.Append("Time : ").AppendLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
|
||||
sb.Append("Method : ").AppendLine(method);
|
||||
sb.Append("Path : ").AppendLine(path ?? string.Empty);
|
||||
sb.Append("Status : ").AppendLine(statusCode.ToString());
|
||||
sb.AppendLine(Bar);
|
||||
sb.AppendLine("Request");
|
||||
sb.AppendLine(Bar);
|
||||
sb.AppendLine(string.IsNullOrEmpty(requestContent) ? "(empty)" : requestContent);
|
||||
sb.AppendLine();
|
||||
sb.AppendLine(Bar);
|
||||
sb.AppendLine("Response");
|
||||
sb.AppendLine(Bar);
|
||||
sb.AppendLine(string.IsNullOrEmpty(responseContent) ? "(empty)" : responseContent);
|
||||
sb.AppendLine();
|
||||
sb.AppendLine(Bar);
|
||||
sb.Append("SQL (").Append(sqlStatements.Count).AppendLine(")");
|
||||
sb.AppendLine(Bar);
|
||||
if (sqlStatements.Count == 0)
|
||||
{
|
||||
sb.AppendLine("(no database commands)");
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var i = 0; i < sqlStatements.Count; i++)
|
||||
{
|
||||
sb.Append('[').Append(i + 1).AppendLine("]");
|
||||
sb.AppendLine(sqlStatements[i]);
|
||||
if (i < sqlStatements.Count - 1)
|
||||
{
|
||||
sb.AppendLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sb.AppendLine(Thick);
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace WmsLite.Api.Infrastructure.HttpLogging;
|
||||
|
||||
/// <summary>
|
||||
/// HTTP 请求/响应日志(中间件)配置。
|
||||
/// </summary>
|
||||
public class HttpLoggingOptions
|
||||
{
|
||||
public const string SectionName = "HttpLogging";
|
||||
|
||||
/// <summary>是否启用中间件记录。</summary>
|
||||
public bool Enabled { get; set; } = true;
|
||||
|
||||
/// <summary>是否将访问信息写入 http_access_log 表(不包含 SQL)。</summary>
|
||||
public bool PersistToDatabase { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 路径(Path)包含任一子串时,将 POST/PUT/PATCH/DELETE 视为「类查询」:不落库、不打印响应体。
|
||||
/// 默认含分页列表常见片段,与约定「变更类方法记响应」配合使用;空数组表示关闭白名单。
|
||||
/// </summary>
|
||||
public string[] PathsOmittingResponseBody { get; set; } = ["paged-list", "pagedlist"];
|
||||
|
||||
/// <summary>路径包含任一子串时不记录/不落库请求体(如登录)。</summary>
|
||||
public string[] PathsOmittingRequestBody { get; set; } = ["/api/Auth/login"];
|
||||
|
||||
/// <summary>JSON 日志脱敏字段名(小写比较)。</summary>
|
||||
public string[] SensitiveFieldNames { get; set; } = ["password", "token", "authorization", "accessToken", "refreshToken"];
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using WmsLite.Api.Models;
|
||||
using WmsLite.Api.Repositories.Interfaces;
|
||||
|
||||
namespace WmsLite.Api.Infrastructure.HttpLogging;
|
||||
|
||||
/// <summary>
|
||||
/// 记录 HTTP 方法、状态码、请求/响应正文(约定:GET/HEAD/OPTIONS 仅记请求;POST/PUT/PATCH/DELETE 记请求+响应;
|
||||
/// 路径命中 PathsOmittingResponseBody 时 POST 等也不记响应体)、与 ILogger 格式化日志;可选写入 http_access_log(不含 SQL)。
|
||||
/// </summary>
|
||||
public sealed class HttpRequestResponseLoggingMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly HttpLoggingOptions _options;
|
||||
private readonly ILogger<HttpRequestResponseLoggingMiddleware> _logger;
|
||||
private readonly IServiceScopeFactory _scopeFactory;
|
||||
|
||||
public HttpRequestResponseLoggingMiddleware(
|
||||
RequestDelegate next,
|
||||
IOptions<HttpLoggingOptions> options,
|
||||
ILogger<HttpRequestResponseLoggingMiddleware> logger,
|
||||
IServiceScopeFactory scopeFactory)
|
||||
{
|
||||
_next = next;
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
_scopeFactory = scopeFactory;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
{
|
||||
await _next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
HttpSqlLogContext.StartRequest(context);
|
||||
|
||||
var request = context.Request;
|
||||
var pathValue = request.Path.Value ?? string.Empty;
|
||||
var omitRequestBody = ShouldOmitRequestBody(pathValue);
|
||||
var requestContentRaw = await ReadRequestContentAsync(request);
|
||||
var requestContent = omitRequestBody
|
||||
? "(omitted: sensitive path — request body not logged)"
|
||||
: SanitizeForLog(requestContentRaw);
|
||||
var sw = Stopwatch.StartNew();
|
||||
|
||||
var originalBody = context.Response.Body;
|
||||
await using var buffer = new MemoryStream();
|
||||
context.Response.Body = buffer;
|
||||
|
||||
try
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
finally
|
||||
{
|
||||
sw.Stop();
|
||||
buffer.Position = 0;
|
||||
var captureResponse = ShouldCaptureResponseBody(request.Method, pathValue, out var responseOmittedReason);
|
||||
string responseText;
|
||||
if (captureResponse)
|
||||
{
|
||||
responseText = await ReadStreamAsStringAsync(buffer);
|
||||
}
|
||||
else
|
||||
{
|
||||
responseText = string.Empty;
|
||||
}
|
||||
|
||||
buffer.Position = 0;
|
||||
await buffer.CopyToAsync(originalBody);
|
||||
context.Response.Body = originalBody;
|
||||
|
||||
var responseForLog = captureResponse
|
||||
? SanitizeForLog(responseText)
|
||||
: responseOmittedReason;
|
||||
|
||||
var sql = HttpSqlLogContext.GetSqlSnapshot(context);
|
||||
var formatted = HttpAccessLogFormatter.Build(
|
||||
request.Method,
|
||||
request.Path.Value,
|
||||
context.Response.StatusCode,
|
||||
requestContent,
|
||||
responseForLog,
|
||||
sql);
|
||||
|
||||
_logger.LogInformation("{AccessLog}", formatted);
|
||||
|
||||
if (_options.PersistToDatabase)
|
||||
{
|
||||
await TryPersistAccessLogAsync(
|
||||
context,
|
||||
request,
|
||||
requestContent,
|
||||
captureResponse ? responseText : null,
|
||||
sw.ElapsedMilliseconds,
|
||||
omitRequestBody);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 约定:GET/HEAD/OPTIONS 只记请求;POST/PUT/PATCH/DELETE 记请求+响应。
|
||||
/// 例外:路径命中 <see cref="HttpLoggingOptions.PathsOmittingResponseBody"/> 时视为查询型接口,不记响应体。
|
||||
/// </summary>
|
||||
private bool ShouldCaptureResponseBody(string method, string pathValue, out string omittedReason)
|
||||
{
|
||||
omittedReason = string.Empty;
|
||||
var m = method.ToUpperInvariant();
|
||||
if (HttpMethods.IsGet(m) || HttpMethods.IsHead(m) || HttpMethods.IsOptions(m))
|
||||
{
|
||||
omittedReason = "(omitted: GET/HEAD/OPTIONS — request only)";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (m is not ("POST" or "PUT" or "PATCH" or "DELETE"))
|
||||
{
|
||||
omittedReason = "(omitted: only POST/PUT/PATCH/DELETE capture response body)";
|
||||
return false;
|
||||
}
|
||||
|
||||
var keywords = _options.PathsOmittingResponseBody;
|
||||
if (keywords is { Length: > 0 })
|
||||
{
|
||||
foreach (var k in keywords)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(k))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (pathValue.Contains(k.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
omittedReason = "(omitted: path matches PathsOmittingResponseBody whitelist)";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task TryPersistAccessLogAsync(
|
||||
HttpContext context,
|
||||
HttpRequest request,
|
||||
string requestContentForDisplay,
|
||||
string? responseText,
|
||||
long elapsedMs,
|
||||
bool omitRequestBody)
|
||||
{
|
||||
try
|
||||
{
|
||||
var queryForDb = request.QueryString.HasValue ? request.QueryString.Value : null;
|
||||
string? bodyForDb;
|
||||
if (HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method) || HttpMethods.IsOptions(request.Method))
|
||||
{
|
||||
bodyForDb = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
bodyForDb = omitRequestBody || string.IsNullOrEmpty(requestContentForDisplay)
|
||||
? null
|
||||
: requestContentForDisplay;
|
||||
}
|
||||
|
||||
var entity = new HttpAccessLog
|
||||
{
|
||||
TraceId = context.TraceIdentifier,
|
||||
HttpMethod = request.Method,
|
||||
Path = request.Path.Value ?? string.Empty,
|
||||
QueryString = string.IsNullOrEmpty(queryForDb) ? null : queryForDb,
|
||||
StatusCode = context.Response.StatusCode,
|
||||
RequestBody = bodyForDb,
|
||||
ResponseBody = responseText is null || string.IsNullOrEmpty(responseText)
|
||||
? null
|
||||
: SanitizeForLog(responseText),
|
||||
DurationMs = elapsedMs > int.MaxValue ? int.MaxValue : (int)elapsedMs,
|
||||
ClientIp = GetClientIp(context),
|
||||
UserId = context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value
|
||||
?? context.User?.FindFirst("sub")?.Value
|
||||
};
|
||||
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var repo = scope.ServiceProvider.GetRequiredService<IHttpAccessLogRepository>();
|
||||
await repo.InsertAsync(entity);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "写入 http_access_log 失败。");
|
||||
}
|
||||
}
|
||||
|
||||
private bool ShouldOmitRequestBody(string pathValue)
|
||||
{
|
||||
var keywords = _options.PathsOmittingRequestBody;
|
||||
if (keywords is not { Length: > 0 })
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var k in keywords)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(k) && pathValue.Contains(k.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private string SanitizeForLog(string? content)
|
||||
{
|
||||
if (string.IsNullOrEmpty(content))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var lower = content.ToLowerInvariant();
|
||||
foreach (var field in _options.SensitiveFieldNames ?? [])
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(field))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lower.Contains($"\"{field.Trim().ToLowerInvariant()}\"", StringComparison.Ordinal))
|
||||
{
|
||||
return "(redacted: sensitive fields)";
|
||||
}
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
private static string? GetClientIp(HttpContext context)
|
||||
{
|
||||
var forwarded = context.Request.Headers["X-Forwarded-For"].ToString();
|
||||
if (!string.IsNullOrWhiteSpace(forwarded))
|
||||
{
|
||||
var first = forwarded.Split(',')[0].Trim();
|
||||
if (!string.IsNullOrEmpty(first))
|
||||
{
|
||||
return first;
|
||||
}
|
||||
}
|
||||
|
||||
return context.Connection.RemoteIpAddress?.ToString();
|
||||
}
|
||||
|
||||
private static async Task<string> ReadRequestContentAsync(HttpRequest request)
|
||||
{
|
||||
if (HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method) || HttpMethods.IsOptions(request.Method))
|
||||
{
|
||||
return request.QueryString.HasValue ? request.QueryString.Value! : string.Empty;
|
||||
}
|
||||
|
||||
request.EnableBuffering();
|
||||
request.Body.Position = 0;
|
||||
using var reader = new StreamReader(
|
||||
request.Body,
|
||||
Encoding.UTF8,
|
||||
detectEncodingFromByteOrderMarks: false,
|
||||
bufferSize: 1024,
|
||||
leaveOpen: true);
|
||||
var body = await reader.ReadToEndAsync();
|
||||
request.Body.Position = 0;
|
||||
return body;
|
||||
}
|
||||
|
||||
private static async Task<string> ReadStreamAsStringAsync(Stream stream)
|
||||
{
|
||||
if (stream.Length == 0)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
stream.Position = 0;
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true);
|
||||
return await reader.ReadToEndAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace WmsLite.Api.Infrastructure.HttpLogging;
|
||||
|
||||
/// <summary>
|
||||
/// 将当前请求内 SqlSugar 产生的 SQL 收集到 <see cref="HttpContext.Items"/>,供 HTTP 日志合并输出。
|
||||
/// </summary>
|
||||
public static class HttpSqlLogContext
|
||||
{
|
||||
public const string ItemsKey = "WmsLite.HttpSqlLogBuffer";
|
||||
|
||||
public sealed class Buffer
|
||||
{
|
||||
private readonly List<string> _sql = new();
|
||||
private readonly object _gate = new();
|
||||
|
||||
public void Append(string sql)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(sql))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
_sql.Add(sql.Trim());
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<string> Snapshot()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _sql.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void StartRequest(HttpContext context)
|
||||
{
|
||||
context.Items[ItemsKey] = new Buffer();
|
||||
}
|
||||
|
||||
public static void Append(HttpContext? context, string executableSql)
|
||||
{
|
||||
if (context?.Items[ItemsKey] is Buffer buffer)
|
||||
{
|
||||
buffer.Append(executableSql);
|
||||
}
|
||||
}
|
||||
|
||||
public static IReadOnlyList<string> GetSqlSnapshot(HttpContext context)
|
||||
{
|
||||
return context.Items[ItemsKey] is Buffer b ? b.Snapshot() : System.Array.Empty<string>();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user