Search code examples
javascriptjsonjsonpcsrf

Is it safe to serve jsonp if I require authentication headers?


I want to serve jsonp so other sites can get json data from my site. I understand that this would be dangerous if I used cookies to authenticate users, because browsers would send the cookies with all requests to my site, so a malicious page could make authenticated requests on my users' behalves without asking them.

All requests to my service have to be authenticated with a special header set on the request, X-AG-AUTH. A secret token identifying the user must be set in that header.

Would a malicious site be able to get data from my service via jsonp without the user providing the secret token?


Solution

  • Well, requiring a custom header for a jsonp call would render the jsonp call useless for requests coming from other domains, because your callers wouldn't be able to set those headers.

    You could use a somewhat similar approach: require a CSRF-prevention-style token passed as a parameter in a POST request. This would require you to share both the logic for generating these tokens and a secret key with each site you want to allow to call your endpoint. Of course, if any of those keys were ever compromised on the remote server's side, you probably wouldn't know about it until it was too late.

    If you're willing to forgo functionality for folks with really old browsers, you could use regular JSON over CORS* with a parser-breaking prefix to prevent cross-site script inclusion.

    I'm assuming your data is not something you want to be made public, in which case you're hopefully also requiring SSL.