我想为来自 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/