CORS (Cross-origin resource sharing) provides the facility to manage who can access the server and run operations on it. CORS enable via reading the HTTP header content from the incoming requests. Only the requests from the same server are allowed to perform operations by default.
Following is an example of a CORS policy:
The above policy allows requests from any origin to perform "GET", "PUT," "HEAD" and "POST" operations on the server.
How to access the AWS S3 bucket policy
1, Go to your S3 bucket and click on the
2, Scroll and find the
Cross-origin resource sharing (CORS) section and click on the "Edit" button.
3, Paste the following sample code as mentioned earlier inside the text field and hit "Save".
This enables all requests to perform "GET", "HEAD", "PUT" and "POST operations to be accepted by the server regardless of their origin.
The above example policy gives almost full access to any request and should not be used in real world projects . You should write policies that limit access to the which are strictly required.
Configuring CORS alone won't give the public access to the objects inside the bucket as AWS has other safety measures. For authorising public access, read my article below:
We can write up to 100 rules as separate objects in the array for different configurations. For example,
The above policy limits the "POST", "PUT", and "DELETE" operations strictly to requests from "www.sharooq.com" origin. However, we can perform the "GET" and "HEAD" operations from any origin. This is an example of how you should be using CORS in real projects.
It is best practice to limit access to a minimum needed for performing required functions.
Components of a CORS policy rule
The following are the main properties of a CORS rule.
This specifies which headers are allowed to send a preflight request to the server. In the above example, we have used a "*" character indicating a wildcard value which enables all headers to be allowed.
Specifies the allowed HTTP operations that an origin can perform. We use the "GET" request to access items in the bucket which is commonly used in the front-end of an application. Methods like "PUT", "DELETE", "POST", etc are destructive operations (makes changes to data) and are mostly accessed from the back-end of the application. You got the idea!!
This indicates which origin can perform certain methods you have specified in the policy. You can specify multiple origins as an array or even use a "*" wildcard character to indicate all subdomains from an origin. For example,
"AllowedOrigins": ["https://*.sharooq.com/", "https://www.sharooqsalaudeen.github.io" ]
Note: Each origin in an array can contain only 1 "*" wildcard charater.
Specifies the time a browser caches the S3 response for a preflight request. Its value is defined in seconds.
Using CORS (Cross-origin resource sharing) we can configure the level of access each origin have on the server or in this case, the S3 bucket.