Enabling cross-origin access for microservices

Browsers are generally restricted when client-side web applications running from one origin request data from another origin. Enabling cross-origin access is generally termed as CORS (Cross-Origin Resource Sharing).

Enabling cross-origin access for microservices

This example shows how to enable cross-origin requests. With microservices, as each service runs with its own origin, it will easily get into the issue of a client-side web application consuming data from multiple origins. For instance, a scenario where a browser client accessing Customer from the Customer microservice and Order History from the Order microservices is very common in the microservices world.

Spring Boot provides a simple declarative approach to enabling cross-origin requests. The following example shows how to enable a microservice to enable cross-origin requests:

@RestController
class GreetingController{
  @CrossOrigin
  @RequestMapping("/")
  Greet greet(){
    return new Greet("Hello World!");
  }
}

By default, all the origins and headers are accepted. We can further customize the cross-origin annotations by giving access to specific origins, as follows. The @CrossOrigin annotation enables a method or class to accept cross-origin requests:

@CrossOrigin("http://mytrustedorigin.com")

Global CORS can be enabled using the WebMvcConfigurer bean and customizing the addCorsMappings(CorsRegistry registry) method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.109.21