Why do browsers have Same-Origin policies when workarounds like JSONP and CORS exist?

前端 未结 1 690
青春惊慌失措
青春惊慌失措 2021-01-14 18:25

This question is kind of a duplicate of: Why same origin policy for XMLHttpRequest

However, this answer isn\'t satisfactory because it doesn\'t address the fact that

1条回答
  •  心在旅途
    2021-01-14 19:11

    Your premise is incorrect. The Same Origin Policy says nothing about the ability of a web page to include resources on an external domain. It prevents direct access to resources via scripting that are owned by different Origins without them opting in.

    Therefore CORS and JSONP are not workarounds for the Same Origin Policy. CORS enables an Origin to opt in to XHR requests with responses, and JSONP is simply a hack to allow an external reference to return dynamic data to the page.

    The point here is to secure your page so that XSS is not possible in the first place. To do this the focus should be on correctly encoding text that is output to the page. This will prevent 'phoning home' as an attack will not be possible in the first place. A Content Security Policy can help neutralise any script that manages to slip through the net. A regular security vulnerability assessment on your website should pickup unencoded output - think of the CSP as filling in the gaps between when these are found and fixed, although browser support is not fully there yet - especially with Internet Explorer.

    However, XMLHttpRequest does not allow this, so Company.com must use JSONP, but this would prevent the scrubbing of data and could result in an Attacker injecting arbitrary Javascript onto the page. How is this a better solution?

    It is not. CORS is a better solution as the request retrieves data rather than executable code. CORS allows XMLHttpRequest to do this.

    With the CORS response header Access-Control-Allow-Origin the website owner of example.com could set this to

    Access-Control-Allow-Origin: https://company.com 
    

    to allow only company.com client-side access to the data over HTTPS via a user's browser.

    In this CORS scenario, example.com is trusting company.com with the data response for that particular request only. In combination with the Access-Control-Allow-Credentials header they can optionally request any authorisation cookies from the user at their browser be sent with the request, and the response to be read by JavaScript at company.com.

    In a JSONP scenario, company.com would be trusting example.com with their whole Origin. This means they are trusting example.com with the whole client site security model. Example.com could do anything it wants to company.com's site. So if example.com is compromised by hackers, they could also control company.com user sessions once each user visits the page containing the

提交回复
热议问题