Home  >  Article  >  Web Front-end  >  Detailed introduction to CORS cross-domain resource sharing (with code)

Detailed introduction to CORS cross-domain resource sharing (with code)

不言
不言forward
2019-03-12 16:55:312057browse

This article brings you a detailed introduction to CORS cross-domain resource sharing (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Understand the same-origin policy

Source (origin)*: It is the protocol, domain name and port number; Same-origin: It means the same source, that is, the protocol, domain name and port are exactly the same; Same-origin policy : The same-origin policy is a security feature of the browser. Client scripts from different origins cannot read or write each other's resources without explicit authorization;

Classification of the same-origin policy:

DOM same-origin policy: For DOM, it is forbidden to operate DOM of different source pages; for example, iframes with different domain names restrict mutual access. XMLHttpRequest Origin Policy: It is prohibited to use XHR objects to initiate HTTP requests to server addresses with different origins.

is not restricted by the same-origin policy:

Links, redirects and form submissions in the page (because after form submission and data submission to the action domain, the page itself has nothing to do with it. It does not care about the request result, and all subsequent operations are handed over to the domain in the action) and will not be restricted by the same-origin policy. The introduction of resources is not restricted, but js cannot read and write loaded content: such as , Detailed introduction to CORS cross-domain resource sharing (with code), embedded in the page,

Why cross-domain restrictions

If there is no DOM same-origin policy: then there will be no research on xss, because your website will not be your website, but Everyone, anyone can write a code to operate your website interface

If there is no XMLHttpRequest origin policy, then CSRF (cross-site request forgery) attacks can be easily carried out:

User After logging into my own website page a.com, the user ID is added to the cookie. The user browsed the malicious page b.com and executed the malicious AJAX request code in the page. b.com initiates an AJAX HTTP request to a.com, and the request will also send the cookie corresponding to a.com by default. a.com extracts the user ID from the sent cookie, verifies that the user is correct, and returns the request data in the response; the data is leaked. And because Ajax is executed in the background, this process is invisible to users. (Attachment) With XMLHttpRequest, can the same-origin policy limit CSRF attacks? Don’t forget that there are also things 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

JSONP cross-domain: borrowed from the script tag It is not affected by the browser's same-origin policy and allows cross-domain reference of resources; therefore, script tags can be created dynamically and then the src attribute can be used for cross-domain;

Disadvantages: All websites can get the data, so there is security Sexual issues require both sides of the website to negotiate the identity verification of the basic token. It can only be GET, not POST. Malicious code may be injected and the page content may be tampered with. String filtering can be used to avoid this problem. Server proxy: Browsers have cross-domain restrictions, but servers do not have cross-domain problems, so the server can request resources in the desired domain and then return them to the client. document.domain, window.name, location.hash: Use iframe to solve DOM same-origin policy postMessage: Solve DOM same-origin policy, new solution CORS (cross-domain resource sharing): The key points here

CORS (cross-domain resource sharing)

The standard cross-domain solution provided by HTML5 is a set of control strategies that are followed by browsers and interacts through the HTTP Header; CORS is mainly set through the backend. Configuration items.

CORS is simple to use

As mentioned before, CORS is cross-domain. Well, just set Access-Control-Allow-Origin on the backend: *|[or specific domain name]; first Attempts:

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

Found that some requests can succeed, but some still report errors:

Detailed introduction to CORS cross-domain resource sharing (with code)

The request is blocked by the same-origin policy, and the pre-request response does not pass the check: http The response is not ok?

and it is found that the OPTIONS request is sent:

Detailed introduction to CORS cross-domain resource sharing (with code)

It is found that the CORS specification divides the request into two types Type, one is a simple request, the other is a non-simple request with preflight

Simple request and non-simple request

How the browser determines when sending a cross-domain request:

When the browser sends a cross-domain request, it will first determine whether it is a simple request or a non-simple request. If it is a simple request, the server program will be executed first, and then the browser will determine whether it is cross-domain; and for non-simple requests request, 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 subsequent actual request from occurring. What is a simple request?

The request method is one of the following:

GETHEADPOST

All headers only include the following list (no custom headers):

Cache-ControlContent-LanguageContent-TypeExpiresLast-ModifiedPragma除此之外都是非简单请求

CORS非简单请求配置须知

正如上图报错显示,对于非简单请求,浏览器会先发送options预检,预检通过后才会发送真是的请求;发送options预检请求将关于接下来的真实请求的信息给服务器:

Origin:请求的源域信息
Access-Control-Request-Method:接下来的请求类型,如POST、GET等
Access-Control-Request-Headers:接下来的请求中包含的用户显式设置的Header列表
服务器端收到请求之后,会根据附带的信息来判断是否允许该跨域请求,通过Header返回信息:
Access-Control-Allow-Origin:允许跨域的Origin列表
Access-Control-Allow-Methods:允许跨域的方法列表
Access-Control-Allow-Headers:允许跨域的Header列表,防止遗漏Header,因此建议没有特殊需求的情况下设置为*
Access-Control-Expose-Headers:允许暴露给JavaScript代码的Header列表
Access-Control-Max-Age:最大的浏览器预检请求缓存时间,单位为s

CORS完整配置

koa配置CORS跨域资源共享中间件:
const cors = (origin) => {
    return async (ctx, next) => {
        ctx.set({
            "Access-Control-Allow-Origin": origin, //允许的源
        })
        // 预检请求
        if (ctx.request.method == "OPTIONS") {
            ctx.set({
                'Access-Control-Allow-Methods': 'OPTIONS,HEAD,DELETE,GET,PUT,POST', //支持跨域的方法
                'Access-Control-Allow-Headers': '*', //允许的头
                'Access-Control-Max-Age':10000, // 预检请求缓存时间
                // 如果服务器设置Access-Control-Allow-Credentials为true,那么就不能再设置Access-Control-Allow-Origin为*,必须用具体的域名
                'Access-Control-Allow-Credentials':true // 跨域请求携带身份信息(Credential,例如Cookie或者HTTP认证信息)
            });
            ctx.send(null, '预检请求')
        } else {
            // 真实请求
            await next()
        }
    }
}

export default cors

现在不管是简单请求还是非简单请求都可以跨域访问啦~

跨域时如何处理cookie

cookie:

我们知道http时无状态的,所以在维持用户状态时,我们一般会使用cookie;cookie每次同源请求都会携带;但是跨域时cookie是不会进行携带发送的;

问题:

由于cookie对于不同源是不能进行操作的;这就导致,服务器无法进行cookie设置,浏览器也没法携带给服务器(场景:用户登录进行登录操作后,发现响应中有set-cookie但是,浏览器cookie并没有相应的cookie)

决解:

浏览器请求设置withCredentials为true即可让该跨域请求携带 Cookie;使用axios配置axios.defaults.withCredentials = true服务器设置Access-Control-Allow-Credentials=true允许跨域请求携带 Cookie“积跬步、行千里”—— 持续更新中~,喜欢的话留下个赞和关注哦!

往期经典好文:

服务器(CentOS)安装配置mongodbKoa日志中间件封装开发(log4js)团队合作必备的Git操作使用pm2部署node生产环境

The above is the detailed content of Detailed introduction to CORS cross-domain resource sharing (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete