Does a RESTful API need CORS implementation anytime?
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 {
}
yes, ir you are developing an API and want to make it public and want that mobile users or another site consumers use it you should set CORS for any site(*) , always. here you can read more info :
https://spring.io/understanding/CORS
Edit: This link is working: https://auth0.com/blog/cors-tutorial-a-guide-to-cross-origin-resource-sharing/