AI Hints
Home›Spring Boot Tutorial›API Versioning, CORS and Practice: A Complete Books API
Spring Boot · Lesson 89 of 120

CORS

Calls from other websites.

⏱ 2 min read▶ Video at 1:58:33🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

A web page loaded from one site wants to call our API, on another address. Browsers block that by default, for safety. CORS is how our API says, that site is allowed.

  • A page on another site
  • Browsers block it
  • CORS allows it

How CORS works

The browser sends an Origin header, saying which site the page came from. Our server answers with Access Control Allow Origin, if that site is allowed. If the header is missing, the browser refuses to show the response. Curl, and other servers, don't care about CORS. It's a browser rule.

keyvalue
Originwhere the page came from
Allowed?Access-Control-Allow-Origin
Not allowedbrowser blocks it
curlignores CORS

@CrossOrigin

At Cross Origin allows one origin, our front end on port three thousand. We pretend to be a browser, by sending an Origin header. Run it. The allowed origin gets the books, and an allow origin header. The other site is refused, with four oh three.

BookController.javajava
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class BookController {

    @GetMapping("/books")
    public List<String> books() {
        return List.of("Dune", "Circe");
    }
}
Output
$ curl -i -H "Origin: http://localhost:3000" localhost:8080/books
HTTP/1.1 200
Access-Control-Allow-Origin: http://localhost:3000
Content-Type: application/json

["Dune","Circe"]
$ curl -i -H "Origin: http://other-site.example" localhost:8080/books
HTTP/1.1 403

Invalid CORS request
Also uses _curl.sh
curl -i -H "Origin: http://localhost:3000" localhost:8080/books
curl -i -H "Origin: http://other-site.example" localhost:8080/books

CORS for the whole app

For many controllers, configure CORS once. A Web Mvc Configurer adds CORS mappings. Here, every path under slash api allows one site, and four methods.

WebConfig.javajava
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("https://shop.example.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}

Summary

CORS lets browsers call your API from other sites. Use at Cross Origin, or a global Web Mvc Configurer. Next, some practice.

Key takeaways
  • Origin header
  • @CrossOrigin
  • addCorsMappings
Next up: Practice: A Complete Books API — your turn