Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of CORS cross-domain resource sharing

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "analyzing CORS cross-domain resource sharing". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "analyzing CORS cross-domain resource sharing".

Learn about the same origin strategy

Source (origin) *: protocol, domain name and port number

Homology: the source is the same, that is, the protocol, domain name and port are identical

Same origin policy: the same origin policy is a security feature of the browser. Client scripts from different sources cannot read and write each other's resources without explicit authorization.

Classification of homologous policies:

1. DOM homology policy: for DOM, forbid operations on DOM of different source pages; for example, iframe of different domain names restricts mutual access.

2. XMLHttpRequest same origin policy: prohibit the use of XHR objects to make HTTP requests to server addresses from different sources.

Not subject to the same origin policy:

1. Links in the page, redirects, and form submission (because the form is submitted and the data is submitted to the action domain, the page itself has nothing to do with it, regardless of the result of the request, and the subsequent operations are handed over to the fields in the page) will not be restricted by the same origin policy.

two。 The introduction of resources is unlimited, but js cannot read and write loaded content, such as those embedded in the page

, etc.

Why cross-domain restrictions

If there is no DOM homology strategy: then there will be no xss research, because your website will not be your website, but everyone's, anyone can write a code to operate your website interface.

If there is no XMLHttpRequest homology policy, then CSRF (cross-site request forgery) can be done easily:

1. The user has logged in to his website page a.comjore cookie and added the user ID.

two。 The user browsed the malicious page b.com and executed the malicious AJAX request code in the page.

3. B.com initiates an AJAX HTTP request to a.com, and the request sends the corresponding cookie of a.com at the same time by default.

4. A.com extracts the user ID from the sent cookie, verifies that the user is correct, and the request data is returned in the response; the data is leaked. And because Ajax is executed in the background, this process is imperceptible to users.

(attached) with XMLHttpRequest homology policy, you can restrict CSRF? Don't forget that there are others that are not subject to the same origin policy: form submission and resource introduction (security issues will be studied in the next issue)

Cross-domain solution scheme

1. JSONP cross-domain: learn from the fact that script tags are not affected by the browser's same origin policy and allow cross-domain references to resources; therefore, you can create script tags dynamically and then use the src attribute to cross-domain.

Disadvantages:

1. All websites can get the data, and there are security problems, so both sides of the website need to discuss the authentication of basic token.

two。 It can only be GET, not POST.

3. May be injected with malicious code, tamper with the content of the page, you can use string filtering to avoid this problem.

two。 Server proxy: the browser has cross-domain restrictions, but the server does not have cross-domain problems, so the server can request the resources of the desired domain and return them to the client.

3. Document.domain, window.name, location.hash: resolve the DOM homology strategy with the help of iframe

4. PostMessage: determine the homology strategy of DOM, a new solution

5. CORS (cross-domain resource sharing): the focus here

CORS (cross-domain resource sharing)

The standard cross-domain solution provided by HTML5 is a set of control policies followed by browsers, which interact with each other through HTTP's Header, and mainly set CORS configuration items through the back end.

CORS is easy to use

As mentioned earlier, CORS is cross-domain. Mm-hmm, the backend sets Access-Control-Allow-Origin:* | [or specific domain name] is fine.

First attempt:

App.use (async (ctx,next) = > {ctx.set ({"Access-Control-Allow-Origin": "http://localhost:8088"}))

It is found that some requests can be successful, but some will still report errors:

The request was blocked by the same origin policy, and the pre-requested response failed the check: http did not return ok?

And found that the OPTIONS request was sent:

It is found that the CORS specification divides requests into two types, one is simple requests, and the other is non-simple requests with pre-checking.

Simple request and non-simple request

How to judge how the browser sends cross-domain requests:

When sending a cross-domain request, the browser will first judge whether it is a simple request or a non-simple request. If it is a simple request, it will first execute the server program, and then the browser will determine whether it is cross-domain or not.

For non-simple requests, the browser will send an OPTIONS HTTP request before sending the actual request to determine whether the server can accept the cross-domain request; if not, the browser will directly prevent the actual request from happening.

What is a simple request?

1. The request method is one of the following:

GET

HEAD

POST

two。 All Header are only included in the following list (no custom header):

Cache-Control

Content-Language

Content-Type

Expires

Last-Modified

Pragma

Other than that, they are all non-simple requests.

Notes on configuration of non-simple request for CORS

As the error report in the figure above shows, for non-simple requests, the browser will send options pre-check first, and then send the real request after the pre-check is passed.

Send an options pre-check request to send information about the next real request to the server:

Origin: source domain information of the request Access-Control-Request-Method: the next request type, such as POST, GET, etc. Access-Control-Request-Headers: the Header list explicitly set by the user included in the next request

After receiving the request, the server determines whether the cross-domain request is allowed based on the attached information, and returns the information through Header:

Access-Control-Allow-Origin: allow cross-domain Origin list Access-Control-Allow-Methods: allow cross-domain method list Access-Control-Allow-Headers: allow cross-domain Header list to prevent omission of Header, so it is recommended to set it to * Access-Control-Expose-Headers: allow exposure to JavaScript code Header list Access-Control-Max-Age: browser pre-check request cache time (in s)

Complete configuration of CORS

1. Koa configures CORS cross-domain resource sharing middleware:

Const cors = (origin) = > {return async (ctx, next) = > {ctx.set ({"Access-Control-Allow-Origin": origin, / / allowed source}) / / pre-check request if (ctx.request.method = = "OPTIONS") {ctx.set ({'Access-Control-Allow-Methods':' OPTIONS,HEAD) DELETE,GET,PUT,POST', / / supports cross-domain method 'Access-Control-Allow-Headers':' *', / / allowed header 'Access-Control-Max-Age':10000, / / pre-check request cache time / / if the server sets Access-Control-Allow-Credentials to true Then you can no longer set Access-Control-Allow-Origin to *, and you must use the specific domain name 'Access-Control-Allow-Credentials':true / / cross-domain request to carry identity information (Credential, such as Cookie or HTTP authentication information)}). Ctx.send (null, 'pre-inspection request')} else {/ / Real request await next ()}} export default cors

Now both simple and non-simple requests can be accessed across domains.

How to deal with cookie when crossing domains

Cookie:

We know that http is stateless, so when maintaining user status, we usually use cookie

Cookie will carry every request of the same origin, but cookie will not carry and send it when crossing a domain.

Question:

Because cookie cannot operate on different sources, the server cannot set cookie and the browser cannot carry it to the server (scenario: after the user logs in to log in, he finds that there is a set-cookie in the response, but the browser cookie does not have the corresponding cookie).

Solution:

The browser request sets withCredentials to true to allow the cross-domain request to carry Cookie; using axios configuration axios.defaults.withCredentials = true

The server sets Access-Control-Allow-Credentials=true to allow cross-domain requests to carry Cookie

At this point, I believe you have a deeper understanding of "analyzing CORS cross-domain resource sharing". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report