asp.net-core - 为来自 ASP.NET Core 的所有 JSON 响应添加前缀以防止 XSSI 攻击

标签 asp.net-core

我想为来自 ASP.NET Core 的所有 JSON 响应添加众所周知的字符串 ")]}',\n" 前缀,以防止 XSSI 攻击。 (有关更多详细信息,请参阅https://angular.io/docs/ts/latest/guide/security.html#!#xss。)

如何实现这一点?我认为我应该使用过滤器或中间件,但无法完全找出正确的方法。

最佳答案

是的,可以使用如下所示的中间件或过滤器:

public class EditResponseFilter : Attribute, IAsyncResourceFilter
{
    private const string _prefix = ")]}',\n";

    public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
    {
        var originBody = context.HttpContext.Response.Body;

        var newBody = new MemoryStream();

        //Body replacement is needed to make the response stream readable
        context.HttpContext.Response.Body = newBody;

        await next();

        newBody.Seek(0, SeekOrigin.Begin);

        string json = new StreamReader(newBody).ReadToEnd();

        context.HttpContext.Response.Body = originBody;

        await context.HttpContext.Response.WriteAsync(_prefix + json);
    }
}

关于asp.net-core - 为来自 ASP.NET Core 的所有 JSON 响应添加前缀以防止 XSSI 攻击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44267012/

相关文章:

c# - 通过 TContextService 和 TContextImplementation 对 AddDbContextCheck 进行健康检查

c# - 具有洋葱架构的 Asp.Net Core 中的 NLog

asp.net-core - Kestrel/IIS Express 需要重新启动才能在浏览器中显示编辑的 .cshtml View 更改

c# - 在 Controller 级别将自定义属性添加到遥测请求

c# - 标记助手 `Attributes` 别名

c# - 如何使用复杂对象发出 GET 请求?

c# - ASP.NET 核心 3.1 : Shared Localization not working for version 3. 1

c# - 在 View 中显示模型状态错误?

c# - 有谁知道 EF Core 3.0 中的 IPluralizer、ICandidateNamingService 和 CandidateNamingService 发生了什么?

c# - net core 2.2 到 3.0 身份验证迁移 AddOpenIdConnect