I am running into an CORS issue with an Angular front-end and a C# REST layer running in k8s. I have a general understanding in CORS and understand the error message below means. I need help fixing it.
Error from the UI.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://auth-svc:8080/api/auth.
In the cluster I have a database, .net core RESTful API and a Angular UI (running on nginx) running with a service for each pod. I am communicating to each layer in the stack via the service name and port.
I have enabled any orgin in my REST Layer, which is from what I understand kind of a bad practice.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
I have looked into a few different ways of doing this, one example being here: Angular/C# CORS Issue
What I am failing to understand is how to do this in a "production safe" way. Meaning if this was a production environment how would I enable the communication between the UI/REST and enforce good security practices for my environments inside a cluster? Even if it is not possible on my environment, it would be helpful to know what I should be shooting for instead of "just making it work".
Thanks!
When putting an app together in kubernetes, you would typicall try to make all services available on the same domain using Ingress definitions.
For example, if you have a backend service + deployment for a .NET app hosting APIs and a service + deployment hosting your frontend (e.g. nginx + build output of ng build --prod
), it could look like:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: my-application
spec:
rules:
- host: www.example.com
http:
paths:
- path: /api
backend:
serviceName: api-service
servicePort: 80
- path: /
backend:
serviceName: frontend
servicePort: 80
Such a setup would eliminate cross-origin issues since for the browser using the site, all URLs would be on the same origin.
For developing for such an environment, it makes sense to use Angular's proxy integration so ng serve
would also set up forwarding the /api
routes to an appropriate development endpoint.
Some ingress controllers also support setting CORS headers on endpoints made available over HTTP, so you would not set them in the API service but on the infrastructure / deployment configuration that defines your cluster-external HTTP endpoints and routing. See these annotations for the nginx ingress controller for example.