为什么我们需要CORS?

cors为什么要预检

Have you ever imagined, how web pages like Google load resources like images, fonts and much more across the Internet using requests? And how the resources attached to the requests gets authorised?

您是否曾想过,像Google这样的网页如何使用请求在Internet上加载图像,字体等资源? 以及如何附加请求的资源?

Browsers follow certain security policies to authorize those resources across domains. Security policies on servers reduce the risks associated with requesting assets hosted on a different server.

浏览器遵循某些安全策略来跨域授权这些资源。 服务器上的安全策略降低了与请求托管在其他服务器上的资产相关的风险。

As resources might have malicious content. The Authorization of the resources helps to secure our browser.If the Authorization/validations are not in place, the security of your browser might be at stake.

由于资源可能包含恶意内容。 资源的授权有助于保护我们的浏览器。如果没有授权/验证,则可能危及浏览器的安全。

Let’s dive into this topic a bit more.

让我们进一步探讨这个主题。

什么是CORS? (What is CORS?)

Cross-origin resource sharing (CORS) is a browser mechanism which enables controlled access to resources located outside of your app domain. The request for a resource (like an image or a font) outside of your app origin (domain) is known as a cross-origin request.

跨域资源共享 (CORS)是一种浏览器机制,可实现对位于应用程序域之外的资源的受控访问。 对您的应用来源(域)之外的资源(例如图像或字体)的请求称为跨域请求。

Image for post
Cross-Origin Resource sharing
跨域资源共享

For example,If a request from google.com tries to pickup a resource like an image from somewebsite.com which contains a malicious content like virus.This virus might introduce trojans into our browser which will affect the browser health.

例如,如果google.com的请求试图从somewebsite.com提取图像之类的资源,其中包含诸如病毒之类的恶意内容。此病毒可能会将特洛伊木马引入我们的浏览器,从而影响浏览器的运行状况。

To avoid this browser have some security policy like same-origin-policy that insists the server to accept resources only from same server.

为了避免使用此浏览器,请使用一些安全策略(例如same-origin-policy) ,该策略要求服务器仅接受来自同一服务器的资源。

If browser tries to request across different domains/origins. It should undergone certain screening process.

如果浏览器尝试跨不同的域/源请求。 它应该经过一定的筛选过程。

What is Same-origin policy?

什么是同源政策?

The same-origin policy limits the ability for a website to interact with resources outside of the source domain (Origin). The same-origin policy defined many years ago in response to potentially malicious cross-domain interactions, such as one website stealing private data from another. It generally allows a domain to issue requests to other domains, but not to get access to the responses.

同源策略限制了网站与源域(来源)以外的资源进行交互的能力。 起源于多年前的策略是对潜在的恶意跨域交互 (例如,一个网站从另一个网站窃取私有数据)做出的响应。 通常,它允许一个域向其他域发出请求,但不允许访问响应。

Image for post
Same-origin policy
同源政策

The server will report an error, whenever requests are made across different origins (domains) without cross origin configuration.

每当跨不同来源 (域)发出请求而没有跨来源配置时,服务器将报告错误。

如何检查起源 (How Origins examined)

Origins assessed using the following parameters

使用以下参数评估来源

使用协议 (Using Protocol)

Verifies the host of applications. When one app hosted with HTTPS requests another hosted with HTTP. It identified as two different origins.

验证应用程序的宿主。 当一个由HTTPS托管的应用程序请求另一个由HTTP托管的应用程序时。 它被确定为两个不同的起源

例如 (For example)

https://somewebsite.com trying to get access to http://localhost:3000

https://somewebsite.com尝试访问http:// localhost:3000

使用域 (Using Domain)

Verifies the domain name in applications. When domain 1 receives a request from domain 2. It identified as two different origins.

验证应用程序中的域名。 当 1收到来自域2的请求时。 它被确定为两个不同的起源

例如 (For example)

https://somewebsite.com trying to get access to https://somewebsitey.com

https://somewebsite.com尝试访问https://somewebsitey.com

使用端口 (Using Port)

Verifies the port number of the servers. When two applications hosted on the same server with different instances. It identified as two different origins.

验证服务器的端口号。 当两个应用程序托管在具有不同实例的同一服务器上时。 它被确定为两个不同的起源

例如 (For example)

Server running on port 8082 trying to get access to another app hosted on 8081.

服务器在端口8082上运行,试图访问在8081上托管的另一个应用程序。

我们为什么需要CORS? (Why do we need CORS?)

Using CORS servers specify not just who can get access to its assets, but also tells how to access its assets [Which HTTP request methods are allowed from external resources].

使用CORS服务器不仅可以指定谁可以访问其资产,还可以指示如何访问其资产 [外部资源允许使用哪种HTTP请求方法]。

Cross-origin requests are made using the standard HTTP request methods. Most servers will allow GET requests, meaning they will allow resources from external origins (say, a web page) to read their assets. HTTP requests methods like PATCH, PUT, or DELETE, gets denied to avoid any conflicts.

跨域请求是使用标准HTTP请求方法发出的。 大多数服务器将允许GET请求,这意味着它们将允许来自外部来源 (例如网页)的资源读取其资产。 拒绝HTTP请求方法(例如PATCH,PUT或DELETE),以避免发生任何冲突

However, it also provides a potential for cross-domain based attacks, if a website’s CORS policy is poorly configured and implemented. CORS is not a protection against cross-origin attacks such as cross-site request forgery (CSRF).

但是,如果网站的CORS策略配置和实施不当,它也可能会导致基于跨域的攻击。 CORS并不是针对跨域攻击(例如跨站点请求伪造(CSRF))的保护措施

外部资源允许哪些HTTP请求方法 (which HTTP request methods are allowed from external resources)

CORS如何管理不同来源的请求 (How CORS manage requests across different origins)

HTTP headers associated with a request or a response passed back and forth between your web browser (also called a client and a server) when the web page tries to use resources hosted on a different server. The CORS standard helps to manage cross-origin requests by adding new HTTP headers to the standard list of headers. The HTTP headers added by the CORS standard are :

当网页尝试使用托管在其他服务器上的资源时,与在浏览器(也称为客户端服务器 )之间来回传递的请求或响应相关的HTTP标头。 通过将新的HTTP标头添加到标头的标准列表中,CORS标准有助于管理跨域请求 。 CORS标准添加的HTTP标头是:

  • Access-Control-Allow-Origin

    访问控制允许来源
  • Access-Control-Allow-Credentials

    访问控制允许凭证
  • Access-Control-Allow-Headers

    访问控制允许标题
  • Access-Control-Allow-Methods

    访问控制允许方法
  • Access-Control-Expose-Headers

    访问控制公开标头
  • Access-Control-Max-Age

    访问控制最大年龄
  • Access-Control-Request-Headers

    访问控制请求标头
  • Access-Control-Request-Method

    访问控制请求方法

访问控制允许来源 (Access-Control-Allow-Origin)

The Access-Control-Allow-Origin header allows servers to specify how their resources shared with external domains. When a GET request made to get access to a resource on Server A, Server A will respond with a value for the Access-Control-Allow-Origin header. Many times, this value will be *, meaning that Server A will share the requested resources with any domain on the Internet. Other times, the value of this header set to a particular domain (or list of domains), meaning that Server A will share its resources with that specific domain (or list of domains). The Access-Control-Allow-Origin header is critical to resource security.

Access-Control-Allow-Origin标头允许服务器指定如何与外部域共享其资源。 当发出GET请求以访问服务器A上的资源时,服务器A将使用Access-Control-Allow-Origin标头的值进行响应。 很多时候,该值为* ,这意味着服务器A将与Internet上的任何域共享请求的资源。 在其他时间,此标头的值设置为特定域(或域列表),这意味着服务器A将与该特定域(或域列表)共享其资源。 Access-Control-Allow-Origin标头对于资源安全至关重要。

res.setHeader('Access-Control-Allow-Origin','*');

You can find a brief description of each CORS header using the link CORS Headers.

您可以使用链接C ORS标头找到每个CORS标头的简短说明

飞行前要求 (PRE-FLIGHT REQUESTS)

As mentioned, most servers will allow GET requests but may block requests that modify resources on the server [PUT, POST, DELETE]. Requests first create a sample request to the server to check which methods allowed in the server and then communicates to the client (your web browser). This Sample request is called Preflight.

如前所述,大多数服务器将允许GET请求,但可能会阻止修改服务器上资源的请求[PUT,POST,DELETE]。 请求首先向服务器创建一个示例请求,以检查服务器中允许哪些方法,然后与客户端(您的Web浏览器)进行通信。 此样本请求称为Preflight

Preflight requests use the OPTIONS header. The preflight request is sent before the original request, hence the term preflight. The purpose of the preflight request is to determine whether or not the original request is safe.

预检请求使用OPTIONS标头。 预检请求在原始请求之前发送,因此称为preflight 。 飞行前请求的目的是确定原始请求是否安全。

The server response allowed methods in the headers.

服务器响应允许标题中的方法。

res.setHeader('Access-Control-Allow-METHODS','POST,PUT,PATCH,DELETE,PUT,OPTIONS')

When a request is made using any of the following HTTP request methods, a standard preflight request will be made before the original request.

使用以下任何HTTP请求方法发出请求时,都会在原始请求之前发出标准的预检请求。

  • PUT

  • DELETE

    删除
  • CONNECT

    连接
  • OPTIONS

    选项
  • TRACE

    跟踪
  • PATCH

    补丁

The server will respond to the preflight request and indicate whether or not the original request is safe to proceed or not. If the server specifies, the original request is safe, it will allow the original request. Otherwise, it will block the original request.

服务器将响应预检请求,并指示原始请求是否可以安全进行。 如果服务器指定原始请求是安全的,它将允许原始请求。 否则,它将阻止原始请求。

The error will be displayed like ‘Did not find method in CORS header ‘Access-Control-Allow-Methods’

该错误将显示为“在CORS标头中没有找到方法'Access-Control-Allow-Methods'

Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’

The request methods above aren’t the only thing that will trigger a preflight request. If any of the headers that are automatically set by your browser (i.e., user agent) are modified, that will also trigger a preflight request.

并非只有上述请求方法会触发预检请求。 如果您的浏览器(即用户代理)自动设置的任何标头被修改,这也会触发预检请求

使用Node js实现CORS (Implementation Of CORS using Node js)

Implementing the request headers to set up CORS correctly depends on the language and framework of the backend of the app.

实现请求标头以正确设置CORS取决于应用程序后端的语言和框架。

For example, If you are using Express, you can use CORS middleware, it would have all default configuration.

例如,如果使用Express,则可以使用CORS中间件,它将具有所有默认配置。

To install the cors package.

要安装cors软件包。

npm install cors

Configure cors, by adding a middleware in your index.js.

通过在index.js中添加中间件来配置cors。

app.use(cors());

We can also set up CORS by adding headers in each response.

我们还可以通过在每个响应中添加标头来设置CORS。

const express = require('express');
const cors = require('cors');
const app = express();app.use((req,res,next)=>{
res.setHeader('Access-Control-Allow-Origin','*'); res.setHeader('Access-Control-Allow-Headers','X-Request-With,Accept,Origin,Content-Type,Authorization'); res.setHeader('Access-Control-Allow-METHODS','POST,PUT,PATCH,DELETE,PUT,OPTIONS')
next();})app.get('/check', (req, res, next)=>{
res.json({msg: 'CORS-enabled!'});
});app.listen(4000,()=>{
console.log('Server is listening on port 4000');
});

we can provide exceptions to particular servers by adding

我们可以通过添加特定服务器的例外

res.setHeader(’Access-Control-Allow-Origin’,[’https://domain1.example’,'https://domain2.example');

By understanding security policies like CORS, you can dowdownload assets from external domains without any complications.

通过了解诸如CORS之类的安全策略,您可以从外部域下载资产而不会带来任何麻烦

Thanks for reading.Happy coding 😊.

感谢您的阅读。编码愉快😊。

翻译自: https://medium.com/swlh/why-do-we-need-cors-ff2e0fb14c96

cors为什么要预检

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值