10 Configuring CORS

 

This chapter covers

  • Defining CORS
  • Applying CORS configurations

In this chapter, we discuss cross-origin resource sharing (CORS) and how to apply it with Spring Security. First, what is CORS, and why should you care? The need for CORS stems from web applications. By default, browsers don’t allow requests made for any domain other than the one from which the site is loaded. For example, if you access the site from example.com, the browser won’t let the site make requests to api.example.com. Figure 10.1 illustrates this concept.

Figure 10.1 Cross-origin resource sharing (CORS). When accessed from example.com, the website cannot make requests to api.example.com because they would be cross-domain requests.

We can briefly say that an app uses the CORS mechanism to relax this strict policy and allow requests made between different origins in some conditions. You need to know this because it’s likely you will have to use it for your applications, especially nowadays where the frontend and backend are separate applications. It is common that a frontend application is developed using frameworks such as Angular, ReactJS, or Vue and hosted at a domain such as example.com, but it calls endpoints on the backend hosted at another domain, such as api.example.com.

This chapter provides some examples from which you can learn how to apply CORS policies for your web applications. It also shows how to avoid leaving security breaches in your applications.

10.1 How does CORS work?

10.2 Applying CORS policies with the @CrossOrigin annotation

10.3 Applying CORS using a CorsConfigurer

Summary