Search code examples
.netcorsmicroservicesapi-gatewayocelot

.NET Microservices and CORS


Please, keep in mind that I am just getting to know microservices.
One thing that came to my mind is connecting CORS with microservices.
I'm creating a project using .NET Core 6 as a backend, and Angular as a Frontend,
this part won't be a problem, but CORS and Microservices, ughh :D

The question is: Do I need to create CORS policy inside my microservices or is it unnecessary?
Ocelot will be used to create API Gateway, and I'm confused if CORS is also needed.

I have some experience in creating SPAs and enabling communication with CORS between .NET backend API and Angular client. I have used there CORS Policy, but my uncertainty is about using CORS in microservices.

I searched in Google with various configurations of this question
and nothing noteworthy popped out in front of my eyes.

Please, help me with that :)


Solution

  • If you have an API Gateway in front of all your microservices, then you only need to set CORS in the API Gateway and it would work as if you add CORS Policies to all microservices at once.

                             ┌───────────────┐
                             │               │
                       ┌─────┤ Microservice1 │
    ┌─────────────┐    │     │               │
    │             │    │     └───────────────┘
    │ API-Gateway ┼────┤
    │             │    │     ┌───────────────┐
    └─────────────┘    │     │               │
          ▲            └─────┤ Microservice2 │
          │                  │               │
          │                  └───────────────┘
          │
    Set CORS here
    

    This is the preferred approach because you do not need to spread CORS policies across all microservices.