Prefix all JSON responses from ASP.NET Core to prevent XSSI attacks

匿名 (未验证) 提交于 2019-12-03 01:03:01

问题:

I would like to prefix all JSON responses from ASP.NET Core with the well-known string ")]}',\n", to prevent XSSI attacks. (See https://angular.io/docs/ts/latest/guide/security.html#!#xss for more details.)

How could this be accomplished? I think I should use a filter or middleware, but can't quite work out the correct approach.

回答1:

Yes, it is possible with a middleware or a filter like below:

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);     } }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!