Is JSONP safe to use?

前端 未结 4 1960
南方客
南方客 2020-11-29 18:04

Are there any security issues that should be considered when using JSONP?

4条回答
  •  囚心锁ツ
    2020-11-29 19:03

    There are security issues for both sides. The most serious one is for the site including JSONP.

    If you are including a from another domain (which you do not control), that domain can change up the script at any time. They can make the javascript do anything in the context of your webpage, that your own javascript could do. There is no way around this if you use JSONP. You should look into cross-domain communication using iframes, which is best done by the excellent EasyDXM library.

    If you are offering a webservice that handles JSONP, you have to protect from Cross-Site Request Forgery (CSRF). This is where your webservice returns sensitive information to logged-in users. If a user has logged into your site, any other site can generate a GET request to the JSONP service, and YOUR domain's cookies are submitted with the request -- in essence, authenticating the logged-in user -- except that now, the remote domain gets the response and is able to read the sensitive data!

    The best way to protect against CSRF is to generate a nonce (a hard-to-guess, randomly generated number) and store it in the session. Output this nonce in all your forms on YOUR webpages, and include it in all JSONP requests on YOUR pages. On the server, make sure that the nonce is present and correct in the request (whether it be a GET, POST, etc.) Other domains will be unable to guess this nonce, and thus unable to get the sensitive information, despite the cookies being sent.

    Finally, there is another sort of security issue: JSONP simply does not support user authentication in the browser, of the kind that is possible with OAuth. You can, of course, have the server get some kind of access token (like with OAuth) and use that. However, if you want to do authentication entirely in the browser, you have to use cross-domain communication with iFrames. I think this is how OAuth 2.0 does it. Here's how you set it up: pages hosted on your site have full access to your server. Have a javascript library which loads EasyDXM and uses it to set up a hidden iframe to your site, and talk to it using that.

提交回复
热议问题