Khaitan

Khaitan

1670399823

Cross-Origin Resource Sharing (CORS) Explained

In this tutorial, you'll learn what Cross Origin Resource Sharing (CORS) is and the basic tenets behind CORS as well as some common pitfalls when implementing CORS. CORS is a mechanism that supports secure requests and data transfers from outside origins (domain, scheme, or port).

Table Of Contents:

  • Introduction
  • CORS History
  • CORS preflight request
  • CORS actual request
  • Wildcards in CORS
  • CORS vulnerability
  • Conclusion

For example, example.com uses a text font that's hosted on fonts.com. When visiting, the user's browser will make a request for the font from fonts.com. Because fonts.com and example.com are two different origins, this is a cross-origin request. If fonts.com allows cross-origin resource sharing to example.com, then the browser will proceed with loading the font. Otherwise, the browser will cancel the request.

More concretely, CORS is a way for web servers to say, "Accept cross-origin requests from this origin" or "Do not accept cross-origin requests from this origin."

This is important because cross-origin requests can be quite scary. I could be logged into my bank account, and on visiting a malicious site, it could make requests to the bank's servers without my knowledge. If CORS rules didn't exist, the request would go through —  potentially changing or leaking my account information.

CORS is a protocol that defines the limitations of cross-origin requests. These limitations are enforced by our browsers. As a result, we can still make cross-origin requests while still maintaining a high level of security. By specifying which origins are allowed to make requests and which methods and headers are allowed, the browser ensures that malicious actors can't retrieve sensitive data with cross-origin requests.

CORS History

CORS was invented to extend and add flexibility to the Same Origin Policy (SOP).

The same origin policy is essentially what the name suggests —  resources can only be loaded from the same origin. Two origins are defined as the same if the protocol, port (if specified), and host are the same.

From a technical perspective, an origin can still request a resource from another origin, but the browser prevents the response from being readable.

However, we sometimes need to access resources from other origins —  such as fonts.com. That's where CORS comes in. CORS relaxes the Same Origin Policy by defining trusted or allowed origins, methods, and headers.

CORS Preflight Request

So now, let's get into the actual motion of what happens when requesting resources from another domain.

We've set up an example website where we can see the full CORS motion. This website calls an API on https://api-emailpassword.demo.supertokens.com. Even though both domains are subdomains of demo.supertokens.com, our browsers register them as different origins, and thus, CORS comes into the picture.

During sign-in, if you open the browser's dev tools and see the network tab, you will see the preflight request being made. More specifically, the preflight request is an OPTIONS request made to our API domain with a couple of headers. Let's take a look at what happens when we click sign in -

OPTIONS /auth/signin HTTP/1.1
Host: api-emailpassword.demo.supertokens.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type,fdi-version,rid
Origin: https://emailpassword.demo.supertokens.com

So that's our pre-flight request. Breaking this down, we have four key things to look at.

  • Host - The "host" of the resource that we're requesting. For us, that's api-emailpassword.demo.supertokens.com
  • Access-Control-Request-Method - The method of the request being made by our operation. This can be any of the HTTP request methods, including GET, POST, PUT, DELETE, and CONNECT.
  • Access-Control-Request-Headers - A comma-separated list of HTTP headers that would be used in the actual request.
  • Origin - Where the request is coming from. For us, that's https://emailpassword.demo.supertokens.com

After getting this pre-flight / OPTIONS request, the API server sends over a pre-flight response. Here's our response from api-emailpassword.demo.supertokens.com.

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://emailpassword.demo.supertokens.com/
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,PUT,POST,DELETE
Access-Control-Allow-Headers: content-type,rid,fdi-version,anti-csrf

Let's break this response down.

  • Access-Control-Allow-Origin —  The origins that the API server has whitelisted. Notice that the value of this is the same as our website domain. This tells the browser that the server expects requests from this client.
  • Access-Control-Allow-Credentials —  The server tells us whether the actual request can include cookies or that the response of the actual request can set cookies. In our case, cookies refer to the session tokens of the user, which act as the credentials of the user once they're signed in.
  • Access-Control-Allow-Methods —  A comma-separated list of HTTP methods that the API domain allows for cross-origin requests.
  • Access-Control-Allow-Headers —  A comma-separated list of HTTP headers that the API domain allows for cross-origin requests.

The browser then takes this response from the API server to determine if the actual request should be sent. If the response from the API doesn't include the requested origin, methods, or headers from the preflight request, then the browser will not send the actual request.

CORS Actual Request

If the response from the API includes the requested origin, it's time to send the actual POST request to sign in.

POST /auth/signin HTTP/1.1
Host: http://api-emailpassword.demo.supertokens.com/
content-type: application/json
fdi-version: 1.15
rid: emailpassword
Content-Length: 92
Origin: https://emailpassword.demo.supertokens.com/

Note that the origin and the headers that are sent (fdi-version,
rid, content-type), are whitelisted by the server, and the browser knows this because of the pre-flight response.

Now let's take a look at the response from the server.

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://emailpassword.demo.supertokens.com/
Access-Control-Allow-Credentials: true
front-token: ...
Access-Control-Expose-Headers: front-token, id-refresh-token
Set-Cookie: ...

Here, we get the response from the server with cookies and tokens that allows us to proceed with the sign-in operation. One thing to note is that compared to our pre-flight, we now also have an additional Access-Control-Expose-Headers header.

  • Access-Control-Expose-Headers —  The server indicates which response headers are available for the scripts running in the browser. Interestingly, the reason this exists is not because of security but because of backward compatibility to when CORS did not exist.

With this, we've now completed our first pre-flight request/response, as well as our actual request/response for signing in!

Wildcards in CORS

One common mistake in configuring CORS is around the use of wildcards. Often, developers will elect to use the wildcard, *, when defining the origins, methods, or headers allowed with CORS.

While wildcards will work for simple requests (requests without HTTP cookies or HTTP authentication information), requests with credentials will often encounter a CORS not authorized error.

That's because, in requests with credentials (cookies), the wildcard is treated as the literal method name or origin name "*" without special semantics. This occurs both in Access-Control-Allow-Origin and Access-Control-Allow-Methods, and some browsers like Safari simply don't have support for wildcards at all.

All in all, it's good hygiene to avoid the wildcard and use a comma-separated list when configuring CORS.

CORS Vulnerability

When configured improperly, CORS can lead to major vulnerabilities. Below, we'll list a couple of common issues when configuring CORS.

Mishandling Origin Whitelist

One of the easiest mistakes to make when implementing CORS is mishandling the origin whitelist. When whitelisting origins, it's often easy to do simple matches with URL prefixes or suffixes or using regular expressions. However, this can lead to quite a few issues.

Let's say that we grant access to all websites with the suffix whitelisted-website.com. This makes it easy for us to grant access to api.whitelisted-website.com.

But an attacker could use a website such as maliciouswhitelisted-website.com and gain access.

The best approach here to avoid potential abuse is to explicitly define origins on the whitelist for sensitive operations when implementing CORS —  for example, specify the strings "https://whitelisted-website.com" and "https://api.whitelisted-website.com" which will grant access to only these domains.

Requests With Null Origin

Another common misconfiguration is whitelisting origins with the value null. Browsers might send the value null in the origin header in situations such as:

  • Request with file;
  • Sandboxed cross-origin requests.

In this case, an attacker can use various tricks to generate a request containing the value null as the origin, which is whitelisted in our configurations. For example, the attacker could use the following sandboxed iframe exploit — 

<iframe src="data:text/html" sandbox="allow-scripts allow-top-navigation allow-forms allow-same-origin">
   function reqlistener() {
      console.log(this.responseText)
   }
   var req = new XMLHttpRequest();
   req.onload = reqlistener;
   req.open("GET", 'vulnerable.com/sensitive', true);
   req.withCredentials = true;
   req.send();
</iframe>

Conclusion

We hope this article helps you understand the basic tenets behind CORS as well as some common pitfalls when implementing CORS.

Original article source at https://supertokens.com

#cors

Cross-Origin Resource Sharing (CORS) Explained

Implement CORS in Spring Boot Application

This CORS Interview Questions and Answer covers CORS policy And how to implement it in the spring Boot application. Why CORS is important And how it works is also explained here.

What is CORS
CORS is Cross Origin Resource sharing.

Its a violation of Same origin policy

What is same-origin policy (SOP)

The same-origin policy (SOP) is a web security mechanism built into web browsers that influences how websites can access one another. The concept of same-origin policy was introduced by Netscape Navigator 2.02 in 1995,

Without SOP, a malicious website or web application could access another without restrictions. That would allow attackers to easily steal sensitive information from other websites or even perform actions on other sites without user consent.

SOP does not need to be turned on – it is automatically enabled in every browser that supports it.

The SOP mechanism was designed to protect against attacks such as cross-site request forgery (CSRF), which basically attempt to take advantage of vulnerabilities due to differing origins

What is Origin

Two URLs have the same origin if the protocol, port (if specified), and host are the same for both.

Eg : http://x.y.com/z/page.html

Why we Backend developers need CORS if its implemented at browser level?

Though we are just the backend developers working on backend application but we do have Front end application too .

Now Backend and Front end urls are usually  
http://localhost:8080/rest/api
http://localhost:4200/xyz


We can clearly see difference in origin. Hence when ever Front end tries to call ur rest APi, It fails due to SOP policy saying No “Access-Control-Allow-Origin” header is present on requested resource. Origin 4200 is not allowed access.

Solution is CORS.

Use @CrossOrigin annotation or send Access-Control-Allow-Origin: http://localhost:4200 in your header to allow it


#cors #springboot #elasticsearch  #interviewquestions 

Implement CORS in Spring Boot Application
Elian  Harber

Elian Harber

1664956813

Iris: The Fastest HTTP/2 Go Web Framework

Iris Web Framework

Iris is a fast, simple yet fully featured and very efficient web framework for Go.

It provides a beautifully expressive and easy to use foundation for your next website or API.

package main

import "github.com/kataras/iris/v12"

func main() {
  app := iris.New()
  app.Use(iris.Compression)

  app.Get("/", func(ctx iris.Context) {
    ctx.HTML("Hello <strong>%s</strong>!", "World")
  })

  app.Listen(":8080")
}

As one Go developer once said, Iris got you covered all-round and standing strong over the years.

Some of the features Iris offers:

  • HTTP/2 (Push, even Embedded data)
  • Middleware (Accesslog, Basicauth, CORS, gRPC, Anti-Bot hCaptcha, JWT, MethodOverride, ModRevision, Monitor, PPROF, Ratelimit, Anti-Bot reCaptcha, Recovery, RequestID, Rewrite)
  • API Versioning
  • Model-View-Controller
  • Websockets
  • gRPC
  • Auto-HTTPS
  • Builtin support for ngrok to put your app on the internet, the fastest way
  • Unique Router with dynamic path as parameter with standard types like :uuid, :string, :int... and the ability to create your own
  • Compression
  • View Engines (HTML, Django, Amber, Handlebars, Pug/Jade and more)
  • Create your own File Server and host your own WebDAV server
  • Cache
  • Localization (i18n, sitemap)
  • Sessions
  • Rich Responses (HTML, Text, Markdown, XML, YAML, Binary, JSON, JSONP, Protocol Buffers, MessagePack, Content Negotiation, Streaming, Server-Sent Events and more)
  • Response Compression (gzip, deflate, brotli, snappy, s2)
  • Rich Requests (Bind URL Query, Headers, Form, Text, XML, YAML, Binary, JSON, Validation, Protocol Buffers, MessagePack and more)
  • Dependency Injection (MVC, Handlers, API Routers)
  • Testing Suite
  • And the most important... you get fast answers and support from the 1st day until now - that's six full years!

Learn what others saying about Iris and star this open-source project to support its potentials.

Benchmarks: Jul 18, 2020 at 10:46am (UTC)

📖 Learning Iris

Create a new project

$ mkdir myapp
$ cd myapp
$ go mod init myapp
$ go get github.com/kataras/iris/v12@master # or @v12.2.0-beta5

Install on existing project

$ cd myapp
$ go get github.com/kataras/iris/v12@master

Run

$ go mod tidy -compat=1.19
$ go run .

Iris contains extensive and thorough documentation making it easy to get started with the framework.

 

For a more detailed technical documentation you can head over to our godocs. And for executable code you can always visit the ./_examples repository's subdirectory.

Do you like to read while traveling?

Book cover

You can request a PDF and online access of the Iris E-Book (New Edition, future v12.2.0+) today and be participated in the development of Iris.

🙌 Contributing

We'd love to see your contribution to the Iris Web Framework! For more information about contributing to the Iris project please check the CONTRIBUTING.md file.

List of all Contributors

🛡 Security Vulnerabilities

If you discover a security vulnerability within Iris, please send an e-mail to iris-go@outlook.com. All security vulnerabilities will be promptly addressed.

Download Details:

Author: Kataras
Source Code: https://github.com/kataras/iris 
License: BSD-3-Clause license

#go #golang #cors #jwt #django 

Iris: The Fastest HTTP/2 Go Web Framework

How to Configure CORS in Spring Boot & Spring Security

In this tutorial, you will learn how to configure Cross-Origin Resource Sharing (CORS) with Spring Boot and Spring Security. CORS is an HTTP header-based mechanism that lets you specify in a flexible way what kind of cross-domain requests should be authorized. You will learn how to configure CORS in a Spring Boot application at a controller, method, and global level. You will also learn what to configure when you bring Spring Security into your application.

🔗Resources & Links mentioned in this video:

Github Repo: https://github.com/danvega/spring-security-cors-demo 
Cross-Origin Resource Sharing (CORS) MDN https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS: 

#springsecurity #cors #springboot #security 

How to Configure CORS in Spring Boot & Spring Security
许 志强

许 志强

1661596200

网络安全:什么是 CORS?

如果您从事 Web 开发工作已有一段时间,您可能听说过“CORS”一词。但它到底是什么?为什么你需要知道它?在这篇博文中,我们将讨论什么是 CORS,以及它如何帮助提高您网站的安全性。

定义 CORS

CORS,缩写为“Cross-Origin Resource Sharing”,是一种允许不同域之间共享资源的机制。CORS 指示哪些域可以从浏览器向服务器发出某些请求。例如,如果域 A 上的网站想要向域 B 发出请求,则必须配置 CORS 以使浏览器允许该请求。

什么是 CORS 政策?

CORS 策略是一组指令,指示允许来自哪些域的哪些请求。当浏览器向服务器发出请求时,服务器将检查 CORS 策略以确定该请求是否被允许。如果请求被允许,服务器将处理请求并返回适当的响应。如果请求不被允许,浏览器将收到一条错误消息。

CORS 策略可以非常简单或相当复杂,具体取决于您网站的需求。例如,一个简单的 CORS 策略可能允许来自任何域的所有请求。更复杂的策略可能只允许来自特定域的某些类型的请求。

亚历山大·弗拉德 ( Aleksander Vlad ) 在Unsplash上拍摄的照片

CORS 是如何工作的?

为了确保要发送的数据是安全的,在发送实际请求之前会向服务器发出预检请求。Origin 标头将包含在此请求中。然后服务器将评估请求以确定它是否安全。服务器将发回包含 Access-Control-Allow-Origin 标头的响应。

如果 Origin 标头的值与 Access-Control-Allow-Origin 标头的值匹配,则浏览器将继续请求。如果没有,浏览器将阻止该请求,并且用户将收到一条错误消息。

为什么 CORS 很重要?

CORS 是一个强大的工具,可以帮助提高您网站的安全性。通过仔细配置 CORS 策略,您可以控制允许哪些域向您的网站发出请求。这有助于防止恶意域发出可能危及您网站安全的未经授权的请求。

如果客户在检查您的 CORS 政策后未获批准,则该客户将无法访问您网站的数据和资源。因此,CORS 可以帮助减少您网站上出现安全漏洞的机会。

结论

在本文中,我们简要概述了 CORS。我们已经定义了什么是 CORS 策略、它是如何工作的以及它为什么重要。我希望这篇文章能教会你一些东西。祝你的编码面试好运!

来源:https ://javascript.plainenglish.io/web-security-what-is-cors-4f38aefdb454

#web #cors 

网络安全:什么是 CORS?
Rui  Silva

Rui Silva

1661596140

Segurança Na Web: O Que é CORS?

Se você trabalha com desenvolvimento web há algum tempo, provavelmente já ouviu o termo “CORS”. Mas o que é isso exatamente? E por que você precisa saber disso? Nesta postagem do blog, discutiremos o que é CORS e como ele pode ajudar a melhorar a segurança do seu site.

Definindo CORS

CORS, abreviado para “Cross-Origin Resource Sharing”, é um mecanismo que permite que recursos sejam compartilhados entre diferentes domínios. CORS indica quais domínios podem fazer determinadas solicitações do navegador para o servidor. Por exemplo, se um site do Domínio A deseja fazer uma solicitação ao Domínio B, o CORS deve ser configurado para que o navegador permita a solicitação.

O que é uma Política CORS?

Uma política CORS é um conjunto de diretivas que indicam quais solicitações são permitidas de quais domínios. Quando um navegador faz uma solicitação a um servidor, o servidor verifica a política CORS para determinar se a solicitação é permitida ou não. Se a solicitação for permitida, o servidor processará a solicitação e retornará a resposta apropriada. Se a solicitação não for permitida, o navegador receberá uma mensagem de erro.

As políticas CORS podem ser muito simples ou bastante complexas, dependendo das necessidades do seu site. Por exemplo, uma política CORS simples pode permitir todas as solicitações de qualquer domínio. Uma política mais complexa pode permitir apenas determinados tipos de solicitações de domínios específicos.

Foto de Aleksander Vlad no Unsplash

Como funciona o CORS?

Para garantir que os dados a serem enviados estejam seguros, uma solicitação de comprovação é feita ao servidor antes que a solicitação real seja enviada. O cabeçalho Origin será incluído nesta solicitação. O servidor avaliará a solicitação para determinar se ela é segura ou não. O servidor enviará de volta uma resposta que inclui o cabeçalho Access-Control-Allow-Origin.

Se o valor do cabeçalho Origin corresponder ao valor do cabeçalho Access-Control-Allow-Origin, o navegador prosseguirá com a solicitação. Caso contrário, o navegador bloqueará a solicitação e o usuário receberá uma mensagem de erro.

Por que o CORS é importante?

CORS é uma ferramenta poderosa que pode ajudar a melhorar a segurança do seu site. Ao configurar cuidadosamente sua política CORS, você pode controlar quais domínios têm permissão para fazer solicitações ao seu site. Isso pode ajudar a impedir que domínios mal-intencionados façam solicitações não autorizadas que possam comprometer a segurança do seu site.

Se um cliente não for aprovado após verificar sua política CORS, o cliente não terá acesso aos dados e recursos do seu site. Como resultado, o CORS pode ajudar a reduzir as chances de uma violação de segurança em seu site.

Conclusão

Neste artigo, apresentamos uma breve visão geral do CORS. Definimos o que é uma política CORS, como ela funciona e por que é importante. Espero que este artigo tenha lhe ensinado algo. Boa sorte com suas entrevistas de codificação!

Fonte: https://javascript.plainenglish.io/web-security-what-is-cors-4f38aefdb454

#web #cors 

Segurança Na Web: O Que é CORS?
高橋  花子

高橋 花子

1661592435

Web セキュリティ: CORS とは?

Web 開発にある程度の期間携わっている場合は、「CORS」という用語を聞いたことがあるでしょう。しかし、それは正確には何ですか?そして、なぜあなたはそれについて知る必要があるのですか?このブログ投稿では、CORS とは何か、そして CORS が Web サイトのセキュリティの向上にどのように役立つかについて説明します。

CORS の定義

「Cross-Origin Resource Sharing」の略称である CORS は、異なるドメイン間でリソースを共有できるようにするメカニズムです。CORS は、どのドメインがブラウザーからサーバーに特定の要求を行う可能性があるかを示します。たとえば、ドメイン A の Web サイトがドメイン B にリクエストを送信する場合、ブラウザーがリクエストを許可するには、CORS を構成する必要があります。

CORS ポリシーとは何ですか?

CORS ポリシーは、どのドメインからのどのリクエストが許可されるかを示す一連のディレクティブです。ブラウザがサーバーにリクエストを送信すると、サーバーは CORS ポリシーをチェックして、リクエストが許可されているかどうかを判断します。リクエストが許可された場合、サーバーはリクエストを処理し、適切なレスポンスを返します。リクエストが許可されていない場合、ブラウザはエラー メッセージを受け取ります。

CORS ポリシーは、Web サイトのニーズに応じて、非常に単純または非常に複雑になります。たとえば、単純な CORS ポリシーでは、任意のドメインからのすべてのリクエストを許可できます。より複雑なポリシーでは、特定のドメインからの特定のタイプのリクエストのみを許可する場合があります。

UnsplashのAleksander Vladによる写真

CORS の仕組み

送信されるデータが安全であることを確認するために、実際のリクエストが送信される前にプリフライト リクエストがサーバーに対して行われます。このリクエストには Origin ヘッダーが含まれます。次に、サーバーはリクエストを評価して、安全かどうかを判断します。サーバーは Access-Control-Allow-Origin ヘッダーを含む応答を返します。

Origin ヘッダーの値が Access-Control-Allow-Origin ヘッダーの値と一致する場合、ブラウザーは要求を続行します。そうでない場合、ブラウザはリクエストをブロックし、ユーザーはエラー メッセージを受け取ります。

CORS が重要な理由

CORS は、Web サイトのセキュリティを向上させるのに役立つ強力なツールです。CORS ポリシーを慎重に構成することで、Web サイトへのリクエストを許可するドメインを制御できます。これにより、悪意のあるドメインが Web サイトのセキュリティを危険にさらす可能性のある不正な要求を行うのを防ぐことができます。

CORS ポリシーを確認した後にクライアントが承認されない場合、クライアントは Web サイトのデータとリソースにアクセスできません。その結果、CORS は Web サイトのセキュリティ侵害の可能性を減らすのに役立ちます。

結論

この記事では、CORS の概要を簡単に説明しました。CORS ポリシーとは何か、どのように機能するか、なぜ重要なのかを定義しました。この記事があなたに何かを教えてくれたことを願っています。コーディングの面接で頑張ってください!

ソース: https://javascript.plainenglish.io/web-security-what-is-cors-4f38aefdb454

#web #cors 

Web セキュリティ: CORS とは?

Sécurité Web : Qu'est-ce Que CORS ?

Si vous travaillez avec le développement Web depuis un certain temps, vous avez probablement entendu le terme "CORS". Mais qu'est ce que c'est exactement? Et pourquoi avez-vous besoin de le savoir ? Dans cet article de blog, nous discuterons de ce qu'est CORS et de la manière dont il peut contribuer à améliorer la sécurité de votre site Web.

Définir le CORS

CORS, en abrégé « Cross-Origin Resource Sharing », est un mécanisme qui permet de partager des ressources entre différents domaines. CORS indique quels domaines peuvent faire certaines demandes du navigateur au serveur. Par exemple, si un site Web sur le domaine A veut faire une demande au domaine B, CORS doit être configuré pour que le navigateur autorise la demande.

Qu'est-ce qu'une politique CORS ?

Une stratégie CORS est un ensemble de directives qui indiquent quelles requêtes sont autorisées à partir de quels domaines. Lorsqu'un navigateur fait une demande à un serveur, le serveur vérifie la politique CORS pour déterminer si la demande est autorisée ou non. Si la demande est autorisée, le serveur traitera la demande et renverra la réponse appropriée. Si la demande n'est pas autorisée, le navigateur recevra un message d'erreur.

Les politiques CORS peuvent être très simples ou assez complexes, selon les besoins de votre site Web. Par exemple, une simple stratégie CORS peut autoriser toutes les demandes de n'importe quel domaine. Une politique plus complexe peut n'autoriser que certains types de demandes provenant de domaines spécifiques.

Photo par Aleksander Vlad sur Unsplash

Comment fonctionne CORS ?

Pour s'assurer que les données à envoyer sont sécurisées, une demande de contrôle en amont est faite au serveur avant que la demande réelle ne soit envoyée. L'en-tête Origin sera inclus dans cette requête. Le serveur évaluera ensuite la demande pour déterminer si elle est sûre ou non. Le serveur renverra une réponse qui inclut l'en-tête Access-Control-Allow-Origin.

Si la valeur de l'en-tête Origin correspond à la valeur de l'en-tête Access-Control-Allow-Origin, le navigateur traitera la demande. Sinon, le navigateur bloquera la demande et l'utilisateur recevra un message d'erreur.

Pourquoi le CORS est-il important ?

CORS est un outil puissant qui peut aider à améliorer la sécurité de votre site Web. En configurant soigneusement votre politique CORS, vous pouvez contrôler quels domaines sont autorisés à envoyer des requêtes à votre site Web. Cela peut aider à empêcher les domaines malveillants de faire des demandes non autorisées qui pourraient potentiellement compromettre la sécurité de votre site Web.

Si un client n'est pas approuvé après avoir vérifié votre politique CORS, le client n'aura pas accès aux données et aux ressources de votre site Web. Par conséquent, CORS peut aider à réduire les risques d'atteinte à la sécurité sur votre site Web.

Conclusion

Dans cet article, nous avons donné un bref aperçu de CORS. Nous avons défini ce qu'est une politique CORS, comment elle fonctionne et pourquoi elle est importante. J'espère que cet article vous a appris quelque chose. Bonne chance pour vos entretiens de codage !

Source : https://javascript.plainenglish.io/web-security-what-is-cors-4f38aefdb454

#web #cors 

Sécurité Web : Qu'est-ce Que CORS ?

Seguridad Web: ¿Qué Es CORS?

Si ha estado trabajando con el desarrollo web durante algún tiempo, es probable que haya escuchado el término "CORS". ¿Pero que es exactamente? ¿Y por qué necesitas saberlo? En esta publicación de blog, analizaremos qué es CORS y cómo puede ayudar a mejorar la seguridad de su sitio web.

Definición de CORS

CORS, abreviado para "Cross-Origin Resource Sharing", es un mecanismo que permite compartir recursos entre diferentes dominios. CORS indica qué dominios pueden realizar ciertas solicitudes desde el navegador al servidor. Por ejemplo, si un sitio web en el Dominio A desea realizar una solicitud al Dominio B, se debe configurar CORS para que el navegador permita la solicitud.

¿Qué es una póliza CORS?

Una política CORS es un conjunto de directivas que indican qué solicitudes se permiten desde qué dominios. Cuando un navegador realiza una solicitud a un servidor, el servidor verificará la política CORS para determinar si la solicitud está permitida o no. Si se permite la solicitud, el servidor procesará la solicitud y devolverá la respuesta adecuada. Si no se permite la solicitud, el navegador recibirá un mensaje de error.

Las políticas de CORS pueden ser muy simples o bastante complejas, según las necesidades de su sitio web. Por ejemplo, una política de CORS simple puede permitir todas las solicitudes de cualquier dominio. Una política más compleja puede permitir solo ciertos tipos de solicitudes de dominios específicos.

Foto de Aleksander Vlad en Unsplash

¿Cómo funciona CORS?

Para garantizar que los datos que se enviarán estén seguros, se realiza una solicitud de verificación previa al servidor antes de enviar la solicitud real. El encabezado de origen se incluirá en esta solicitud. Luego, el servidor evaluará la solicitud para determinar si es segura o no. El servidor devolverá una respuesta que incluye el encabezado Access-Control-Allow-Origin.

Si el valor del encabezado Origin coincide con el valor del encabezado Access-Control-Allow-Origin, el navegador procederá con la solicitud. De lo contrario, el navegador bloqueará la solicitud y el usuario recibirá un mensaje de error.

¿Por qué es importante CORS?

CORS es una poderosa herramienta que puede ayudar a mejorar la seguridad de su sitio web. Al configurar cuidadosamente su política de CORS, puede controlar qué dominios pueden realizar solicitudes a su sitio web. Esto puede ayudar a evitar que los dominios maliciosos realicen solicitudes no autorizadas que podrían poner en peligro la seguridad de su sitio web.

Si un cliente no es aprobado después de verificar su política CORS, el cliente no tendrá acceso a los datos y recursos de su sitio web. Como resultado, CORS puede ayudar a reducir las posibilidades de una brecha de seguridad en su sitio web.

Conclusión

En este artículo, hemos dado una breve descripción de CORS. Hemos definido qué es una política CORS, cómo funciona y por qué es importante. Espero que este artículo te haya enseñado algo. ¡Buena suerte con tus entrevistas de codificación!

Fuente: https://javascript.plainenglish.io/web-security-what-is-cors-4f38aefdb454

#web #cors 

Seguridad Web: ¿Qué Es CORS?
Thai  Son

Thai Son

1661588640

Bảo Mật Web: CORS Là Gì?

Nếu bạn đã làm việc với phát triển web trong một khoảng thời gian dài, bạn có thể đã nghe thấy thuật ngữ “CORS”. Nhưng nó là gì, chính xác là gì? Và tại sao bạn cần biết về nó? Trong bài đăng trên blog này, chúng ta sẽ thảo luận về CORS là gì và nó có thể giúp cải thiện tính bảo mật của trang web của bạn như thế nào.

Xác định CORS

CORS, viết tắt của “Cross-Origin Resource Sharing”, là một cơ chế cho phép chia sẻ tài nguyên giữa các miền khác nhau. CORS cho biết miền nào có thể thực hiện các yêu cầu nhất định từ trình duyệt đến máy chủ. Ví dụ: nếu một trang web trên Miền A muốn thực hiện yêu cầu đối với Miền B, CORS phải được định cấu hình để trình duyệt cho phép yêu cầu.

Chính sách CORS là gì?

Chính sách CORS là một tập hợp các chỉ thị cho biết những yêu cầu nào được phép từ miền nào. Khi trình duyệt đưa ra yêu cầu tới máy chủ, máy chủ sẽ kiểm tra chính sách CORS để xác định xem yêu cầu đó có được phép hay không. Nếu yêu cầu được cho phép, máy chủ sẽ xử lý yêu cầu và trả lại phản hồi thích hợp. Nếu yêu cầu không được cho phép, trình duyệt sẽ nhận được thông báo lỗi.

Các chính sách của CORS có thể rất đơn giản hoặc khá phức tạp, tùy thuộc vào nhu cầu của trang web của bạn. Ví dụ: chính sách CORS đơn giản có thể cho phép tất cả các yêu cầu từ bất kỳ miền nào. Chính sách phức tạp hơn có thể chỉ cho phép một số loại yêu cầu nhất định từ các miền cụ thể.

Ảnh của Aleksander Vlad trên Unsplash

CORS hoạt động như thế nào?

Để đảm bảo rằng dữ liệu được gửi đi là an toàn, một yêu cầu preflight được gửi đến máy chủ trước khi yêu cầu thực sự được gửi đi. Tiêu đề Nguồn gốc sẽ được bao gồm trong yêu cầu này. Sau đó máy chủ sẽ đánh giá yêu cầu để xác định xem nó có an toàn hay không. Máy chủ sẽ gửi lại phản hồi bao gồm tiêu đề Access-Control-Allow-Origin.

Nếu giá trị của tiêu đề Origin khớp với giá trị của tiêu đề Access-Control-Allow-Origin, trình duyệt sẽ tiếp tục yêu cầu. Nếu không, trình duyệt sẽ chặn yêu cầu và người dùng sẽ nhận được thông báo lỗi.

Tại sao CORS lại quan trọng?

CORS là một công cụ mạnh mẽ có thể giúp cải thiện tính bảo mật của trang web của bạn. Bằng cách định cấu hình cẩn thận chính sách CORS của mình, bạn có thể kiểm soát miền nào được phép đưa ra yêu cầu đối với trang web của mình. Điều này có thể giúp ngăn các miền độc hại thực hiện các yêu cầu trái phép có thể gây nguy hiểm cho tính bảo mật của trang web của bạn.

Nếu khách hàng không được chấp thuận sau khi kiểm tra chính sách CORS của bạn, khách hàng sẽ không có quyền truy cập vào dữ liệu và tài nguyên của trang web của bạn. Do đó, CORS có thể giúp giảm nguy cơ vi phạm bảo mật trên trang web của bạn.

Sự kết luận

Trong bài viết này, chúng tôi đã đưa ra một cái nhìn tổng quan ngắn gọn về CORS. Chúng tôi đã xác định chính sách CORS là gì, nó hoạt động như thế nào và tại sao nó lại quan trọng. Tôi hy vọng bài viết này đã dạy cho bạn điều gì đó. Chúc may mắn với các cuộc phỏng vấn viết mã của bạn!

Nguồn: https://javascript.plainenglish.io/web-security-what-is-cors-4f38aefdb454

#web #cors 

Bảo Mật Web: CORS Là Gì?

Web Security: What is CORS?

If you’ve been working with web development for any length of time, you’ve likely heard the term “CORS.” But what is it, exactly? And why do you need to know about it? In this blog post, we will discuss what CORS is and how it can help improve the security of your website.

Defining CORS

CORS, abbreviated for “Cross-Origin Resource Sharing”, is a mechanism that allows resources to be shared between different domains. CORS indicates what domains may make certain requests from the browser to the server. For example, if a website on Domain A wants to make a request to Domain B, CORS must be configured in order for the browser to allow the request.

See more at: https://javascript.plainenglish.io/web-security-what-is-cors-4f38aefdb454

#web #cors #security 

Web Security: What is CORS?
Rupert  Beatty

Rupert Beatty

1659144120

Laravel-cors: Adds CORS Headers Support in Your Laravel Application

CORS Middleware for Laravel

About

The laravel-cors package allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration.

If you want to have a global overview of CORS workflow, you can browse this image.

Upgrading from 0.x (barryvdh/laravel-cors)

When upgrading from 0.x versions, there are some breaking changes:

  • A new 'paths' property is used to enable/disable CORS on certain routes. This is empty by default, so fill it correctly!
  • Group middleware is no longer supported, use the global middleware
  • The vendor name has changed (see installation/usage)
  • The casing on the props in cors.php has changed from camelCase to snake_case, so if you already have a cors.php file you will need to update the props in there to match the new casing.

Features

  • Handles CORS pre-flight OPTIONS requests
  • Adds CORS headers to your responses
  • Match routes to only add CORS to certain Requests

Installation

Require the fruitcake/laravel-cors package in your composer.json and update your dependencies:

composer require fruitcake/laravel-cors

If you get a conflict, this could be because an older version of barryvdh/laravel-cors or fruitcake/laravel-cors is installed. Remove the conflicting package first, then try install again:

composer remove barryvdh/laravel-cors fruitcake/laravel-cors
composer require fruitcake/laravel-cors

Global usage

To allow CORS for all your routes, add the HandleCors middleware at the top of the $middleware property of app/Http/Kernel.php class:

protected $middleware = [
  \Fruitcake\Cors\HandleCors::class,
    // ...
];

Now update the config to define the paths you want to run the CORS service on, (see Configuration below):

'paths' => ['api/*'],

Configuration

The defaults are set in config/cors.php. Publish the config to copy the file to your own config:

php artisan vendor:publish --tag="cors"

Note: When using custom headers, like X-Auth-Token or X-Requested-With, you must set the allowed_headers to include those headers. You can also set it to ['*'] to allow all custom headers.

Note: If you are explicitly whitelisting headers, you must include Origin or requests will fail to be recognized as CORS.

Options

OptionDescriptionDefault value
pathsYou can enable CORS for 1 or multiple paths, eg. ['api/*'][]
allowed_originsMatches the request origin. Wildcards can be used, eg. *.mydomain.com or mydomain.com:*['*']
allowed_origins_patternsMatches the request origin with preg_match.[]
allowed_methodsMatches the request method.['*']
allowed_headersSets the Access-Control-Allow-Headers response header.['*']
exposed_headersSets the Access-Control-Expose-Headers response header.false
max_ageSets the Access-Control-Max-Age response header.0
supports_credentialsSets the Access-Control-Allow-Credentials header.false

allowed_origins, allowed_headers and allowed_methods can be set to ['*'] to accept any value.

Note: For allowed_origins you must include the scheme when not using a wildcard, eg. ['http://example.com', 'https://example.com']. You must also take into account that the scheme will be present when using allowed_origins_patterns.

Note: Try to be a specific as possible. You can start developing with loose constraints, but it's better to be as strict as possible!

Note: Because of http method overriding in Laravel, allowing POST methods will also enable the API users to perform PUT and DELETE requests as well.

Note: Sometimes it's necessary to specify the port (when you're coding your app in a local environment for example). You can specify the port or using a wildcard here too, eg. localhost:3000, localhost:* or even using a FQDN app.mydomain.com:8080

Lumen

On Lumen, just register the ServiceProvider manually in your bootstrap/app.php file:

$app->register(Fruitcake\Cors\CorsServiceProvider::class);

Also copy the cors.php config file to config/cors.php and put it into action:

$app->configure('cors');

Global usage for Lumen

To allow CORS for all your routes, add the HandleCors middleware to the global middleware and set the paths property in the config.

$app->middleware([
    // ...
    Fruitcake\Cors\HandleCors::class,
]);

Common problems

Wrong config

Make sure the path option in the config is correct and actually matches the route you are using. Remember to clear the config cache as well.

Error handling, Middleware order

Sometimes errors/middleware that return own responses can prevent the CORS Middleware from being run. Try changing the order of the Middleware and make sure it's the first entry in the global middleware, not a route group. Also check your logs for actual errors, because without CORS, the errors will be swallowed by the browser, only showing CORS errors. Also try running it without CORS to make sure it actually works.

Authorization headers / Credentials

If your Request includes an Authorization header or uses Credentials mode, set the supports_credentials value in the config to true. This will set the Access-Control-Allow-Credentials Header to true.

Echo/die

If you echo(), dd(), die(), exit(), dump() etc in your code, you will break the Middleware flow. When output is sent before headers, CORS cannot be added. When the scripts exits before the CORS middleware finished, CORS headers will not be added. Always return a proper response or throw an Exception.

Disabling CSRF protection for your API

If possible, use a route group with CSRF protection disabled. Otherwise you can disable CSRF for certain requests in App\Http\Middleware\VerifyCsrfToken:

protected $except = [
    'api/*',
    'sub.domain.zone' => [
      'prefix/*'
    ],
];

Duplicate headers

The CORS Middleware should be the only place you add these headers. If you also add headers in .htaccess, nginx or your index.php file, you will get duplicate headers and unexpected results.

Implements https://github.com/fruitcake/php-cors for Laravel

Since Laravel 9.2, this Middleware is included in laravel/framework. You can use the provided middleware, which should be compatible with the Middleware and config provided in this package. See https://github.com/laravel/laravel/pull/5825/files for the changes.

Author: fruitcake
Source Code: https://github.com/fruitcake/laravel-cors 
License: MIT license

#laravel #cors #php #middleware 

Laravel-cors: Adds CORS Headers Support in Your Laravel Application

Cakephp-cors: CORS Plugin for CakePHP 3

CORS plugin for CakePHP 3.0-3.2  

A simple plugin to add CORS headers to specified requests.

For CakePHP 3.3+, use cakephp-cors

Requirements

  • CakePHP 3.0-3.2
  • PHP 5.4+

Installation

You can install this plugin into your CakePHP application using composer.

To install this plugin, in your terminal type:

composer require snelg/cakephp-cors:dev-master

Unlocking CORS for a single controller

Define a single key within the routes array in the DispatcherFactory options array:

DispatcherFactory::add('Cors.Cors', ['routes' => [
    'ControllerClassName'
]]);

Unlocking CORS for a controller scoped to a single action

Define a nested array consisting of 'controller' => 'action' within the routes array in DispatcherFactor options:

DispatcherFactory::add('Cors.Cors', ['routes' => [
    'ControllerClassName' => 'some_action',
]]);

Scoping CORS to particular origins

DispatcherFactory::add('Cors.Cors', ['routes' => [
    'ControllerClassName' => [
        'action_one' => ['origin' => 'somesite.com']
]]);

Scoping CORS to particular methods

DispatcherFactory::add('Cors.Cors', ['routes' => [
   'ControllerClassName' => [
       'action_one' => [
           'origin' => 'somesite.com',
           'methods' => ['PUT', 'DELETE']
       ]
]]);

Setting CORS within Router::connect

Router::scope('/', function ($routes) {
    $routes->connect('/public_api',
    ['controller' => 'ControllerClass', 'action' => 'action_one', 'cors' => true]]
});
}

Router::connect with custom origins, methods, and headers

Router::scope('/', function ($routes) {
    $routes->connect('/public_api', [
        'controller' => 'ControllerClass',
        'action' => 'action_one',
        'cors' => [
            'origin' => 'your_origin.com',
            'methods' => ['PUT', 'DELETE'],
            'headers' => []
        ]
    ]);
});
}

Support

For bugs and feature requests, please use the issues section of this repository.

Contributing

To contribute to this plugin please follow a few basic rules.

Creators

Glen Sawyer && Wes King

Author: snelg
Source Code: https://github.com/snelg/cakephp-cors 
License: MIT License

#php #cakephp #cors 

Cakephp-cors: CORS Plugin for CakePHP 3

A CakePHP (3.3+) Plugin for Activate Cors Domain in Your Application

cakephp-cors

A CakePHP (4+) plugin for activate cors domain in your application with Middleware.

For cake 3.3+ use branch cake-3

Requirements

  • PHP version 7.2 or higher
  • CakePhp 4.0 or higher

Installation

You can install this plugin into your CakePHP application using composer.

The recommended way to install composer packages is:

composer require ozee31/cakephp-cors

Quick Start

Loading the Plugin

// In src/Application.php
public function bootstrap(): void
{
    // code ...
    $this->addPlugin('Cors');
}

By default the plugin authorize cors for all origins, all methods and all headers and caches all for one day.

Configuration

Default configuration

<?php
[
    'AllowOrigin' => true, // accept all origin
    'AllowCredentials' => true,
    'AllowMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], // accept all HTTP methods
    'AllowHeaders' => true, // accept all headers
    'ExposeHeaders' => false, // don't accept personal headers
    'MaxAge' => 86400, // cache for 1 day
    'exceptionRenderer' => 'Cors\Error\AppExceptionRenderer', // Use ExeptionRenderer class of plugin

Change config

In app.php add :

'Cors' => [
    // My Config
]

AllowOrigin (Access-Control-Allow-Origin)

A returned resource may have one Access-Control-Allow-Origin header, with the following syntax:

'Cors' => [
    // Accept all origins
    'AllowOrigin' => true,
    // OR
    'AllowOrigin' => '*',

    // Accept one origin
    'AllowOrigin' => 'http://flavienbeninca.fr'

    // Accept many origins
    'AllowOrigin' => ['http://flavienbeninca.fr', 'http://google.com']
]

AllowCredentials (Access-Control-Allow-Credentials)

The Access-Control-Allow-Credentials header Indicates whether or not the response to the request can be exposed when the credentials flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. Note that simple GET requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not returned with the resource, the response is ignored by the browser and not returned to web content.

'Cors' => [
    'AllowCredentials' => true,
    // OR
    'AllowCredentials' => false,
]

AllowMethods (Access-Control-Allow-Methods)

'Cors' => [
    // string
    'AllowMethods' => 'POST',
    // OR array
    'AllowMethods' => ['GET', 'POST'],
]

AllowHeaders (Access-Control-Allow-Headers)

The Access-Control-Allow-Headers header is used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.

'Cors' => [
    // accept all headers
    'AllowHeaders' => true,

    // accept just authorization
    'AllowHeaders' => 'authorization',

    // accept many headers
    'AllowHeaders' => ['authorization', 'other-header'],
]

ExposeHeaders (Access-Control-Expose-Headers)

The Access-Control-Expose-Headers header lets a server whitelist headers that browsers are allowed to access. For example:

'Cors' => [
    // nothing
    'ExposeHeaders' => false,

    // string
    'ExposeHeaders' => 'X-My-Custom-Header',

    // array
    'ExposeHeaders' => ['X-My-Custom-Header', 'X-Another-Custom-Header'],
]

MaxAge (Access-Control-Max-Age)

The Access-Control-Max-Age header indicates how long the results of a preflight request can be cached. For an example of a preflight request, see the above examples.

'Cors' => [
    // no cache
    'MaxAge' => false,

    // 1 hour
    'MaxAge' => 3600,

    // 1 day
    'MaxAge' => 86400,
]

exceptionRenderer

This option overload default exceptionRenderer in app.php.

By default this class extends from Error.exceptionRenderer to add Cors Headers

If you don't want to overload exceptionRenderer, You must write

'Cors' => [
    'exceptionRenderer' => false
]

Read more

Learn more about CORS

Author: ozee31
Source Code: https://github.com/ozee31/cakephp-cors 
License: MIT license

#php #cakephp #cors 

A CakePHP (3.3+) Plugin for Activate Cors Domain in Your Application
Raja Tamil

Raja Tamil

1652321836

CORS Error & Solutions In A Nutshell [Cross Origin Resource Sharing]

Sometimes, when you’re making an HTTP request to a Third Party Server API or your own API but from a different domain server, you will probably get the annoying CORS error. 

"Access to XMLHttpRequest at 'https://maps.googleapis.com/maps/api/...[YOURAPIKEY]' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." 

✴️ Points 

00.40 Why CORS error is occurring? 
01:40 What is CORS? 
02:03 Find a few ways to fix it!

SUBSCRIBE 👉 https://www.youtube.com/softauthor

#javascript #cors 

CORS Error & Solutions In A Nutshell [Cross Origin Resource Sharing]