c# - 使用 SimpleHtml5Sanitizer C# 清理 JSON 后 JSON 不正确
问题描述
我正在尝试在 Core 2.2 API 中添加 Anti-XSS 中间件。
启动.cs
app.UseAntiXSS();
AntiXssMiddleware.cs
public class AntiXssMiddleware
{
private readonly RequestDelegate _next;
public AntiXssMiddleware(RequestDelegate next)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
_next = next;
}
public async Task Invoke(HttpContext context)
{
// Check XSS in request content
var streamBody = context.Request.Body;
var originalContent = await ReadRequestBody(context);
var notModified = true;
try
{
var json = originalContent;
//json = json.Replace("\"", "'");
int matchIndex;
if (CrossSiteScriptingValidation.IsDangerousString(json, out matchIndex))
{
//json = json.SanitizeHTML();
var sanitizer = HtmlSanitizer.SimpleHtml5Sanitizer();
sanitizer.WhiteListMode = false;
//json = HttpUtility.HtmlDecode(json);
json = sanitizer.Sanitize(json);
json = HttpUtility.HtmlDecode(json);
json = Regex.Unescape(json);
//json = Regex.Unescape(json).Replace("\"\"", "");
var requestData = Encoding.UTF8.GetBytes(json);
streamBody = new MemoryStream(requestData);
context.Request.Body = streamBody;
notModified = false;
}
}
catch
{
//context.Request.Body = streamBody;
//await _next.Invoke(context);
}
if (notModified)
{
var requestData = Encoding.UTF8.GetBytes(originalContent);
streamBody = new MemoryStream(requestData);
}
context.Request.Body = streamBody;
await _next.Invoke(context);
}
private static async Task<string> ReadRequestBody(HttpContext context)
{
var buffer = new MemoryStream();
await context.Request.Body.CopyToAsync(buffer);
context.Request.Body = buffer;
buffer.Position = 0;
var encoding = Encoding.UTF8;
var contentType = context.Request.GetTypedHeaders().ContentType;
//if (contentType?.Charset != null) encoding = Encoding.GetEncoding(contentType.Charset.Value);
var requestContent = await new StreamReader(buffer, encoding).ReadToEndAsync();
context.Request.Body.Position = 0;
return requestContent;
}
}
public static class AntiXssMiddlewareExtensions
{
public static IApplicationBuilder UseAntiXSS(this IApplicationBuilder app)
{
return app.UseMiddleware<AntiXssMiddleware>();
}
}
我尝试了各种库,例如 AntiXSS、SimpleHTML5Sanitizer,但都是同样的问题。在我清理 HTML 后,没有得到正确格式化的 JSON。
注意:-我正在清理 JSON 正文,其中包含一些具有 HTML 的属性。
解决方案
推荐阅读
- node.js - 使用 Mongoose/Express/Node 在一个 POST 路由中保存多个模型文档
- javascript - 访问新创建的 div 文本中的数据属性
- python - Python 乌龟 end_poly() 不起作用
- git - 如何在浏览器中使用 gerrit 创建更改
- playframework - 从 Source 构建时未找到 Play Framework 版本文件
- python - 如何从 python 上的文件中快速获取值?
- python - Asyncio Python 应用在 Heroku 上运行缓慢
- javascript - 未使用 javascript 设置 Samesite cookie 属性
- python - 尝试将 Maxcor 传递到 L-BFGS-B 最小化器时出现 TypeError
- c# - 将带有列表的对象转换回类并从对象中查找特定数据