Sörnt Sörnt - 10 months ago 127
AngularJS Question

ServiceStack with AngularJS: JSON Vulnerability Protection and XSRF

The AngularJS documentation provides some recommendation to protect a web side against JSON Vulnerability and XSRF Attacks (https://docs.angularjs.org/api/ng/service/$http section "Security Considerations").

How can I configure the JSON serialize to prefix my JSON?
What is the best way to get a verifiable value for the "X-XSRF-TOKEN" token value and how to validate that for each request?


You can add a GlobalResponseFilter to prefix your JSON with:

this.GlobalResponseFilters.Add((req, res, dto) =>
    if (req.ResponseContentType.MatchesContentType(MimeTypes.Json) 
        && !(dto is IHttpResult))

Which will write the recommended prefix before the serialized JSON response.

This will protect against JS Array vulnerability, an alternative approach would be to wrap array responses in a DTO, e.g:

return new Response { Results = Db.Select<Poco>() };

Which would serialize as a JSON object avoids the JS Array vulnerability.

I prefer returning object responses since it doesn't limit your JSON services to only work with appropriately configured JS Apps and object responses are more forward-compatible/future-proofed as you can later modify the service to return multiple return types without breaking compatibility with existing clients.

Any random string should make a good token, e.g. hex-encoded random bytes or just a new Guid.