Marco Rehmer
Marco Rehmer

Reputation: 1093

Does a RESTful API need CORS implementation anytime?

I struggle around with CORS implementation in my client-server project. CORS means, that calls from other origins (ex. other domain) only allowed if the header contains the CORS value.

So, for example if I host a website on www.domain.com and call an RESTful API on the same domain, everything is fine.

But if I develop an API for an mobile application for example, the mobile does not have the same domain of the API. How could that work together? Does I need everytime the CORS implementation in my service?

The question comes up, since I develop an Angular 2 application, that is running in dev on localhost:4200 and my API runs on localhost:8080 (build with Spring Boot). So the client throws an exception, because it's not the same origin (different port).

The Goal is to host my API on an root server somewhere in the internet, and the client on different webspace provider (because it's just a single Page Application). The api runs with http://1.2.3.4:8080/api/v1 and the client with http://www.example.com:80/myPage

So, does I need to implement Cross-Origin everytime? Or is there another way to realize that?

Upvotes: 16

Views: 29965

Answers (2)

Cristian Sepulveda
Cristian Sepulveda

Reputation: 1730

Yes, if you are developing an API and want to make it public and want mobile users or other site consumers use it, you should set CORS for any site (*) , always. You can read more info here:

https://spring.io/understanding/CORS (no longer functioning)

https://auth0.com/blog/cors-tutorial-a-guide-to-cross-origin-resource-sharing/

Upvotes: 8

Manikandan Jeyarajan
Manikandan Jeyarajan

Reputation: 104

Due to security concerns, browsers enforce same-origin policy i.e., a script (typically AJAX calls) running in a web page cannot access data from another page residing in a different domain. In some cases, this can be restrictive. CORS (Cross Origin resource sharing) is a W3C specification supported by most modern browsers to specify when it is safe to allow cross origin requests.

In Spring boot, enabling CORS is as easy as adding the @CrossOrigin annotation. This annotation can be added at method level to enable just for that particular request mapping or at the class level to enable for the whole controller.

You could list the domain and port to be allowed by adding an "origins" attribute to the annotation. If it is not specified, all origins are allowed by default (better to avoid this for security reasons).

Below is an example to enable CORS for example.com domain and port 80 at controller level

@CrossOrigin(origins = "http://www.example.com:80")
@RestController
@RequestMapping("/yourmapping")
public class YourController {

}

Upvotes: 8

Related Questions