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