Verify CORS origin in .net 6 when DI is needed

113 Views Asked by At

Our service allows the customers to enter their own domain to access the service, after setting the proper DNS records. Their domain/subdomain is pointed to our front end server which makes it more personalized for their users.

Since any customer can change their domain at any time, or even add new ones, we need to make a database call to verify the origin-header.

I've been trying to simply NOT handle cors as usual (app.UseCors() etc.), but instead using filters to resolve the "header-situation". I gave up on this approach because I realized that it just won't work (no endpoint with "OPTIONS" allowed). It also feels dirty, even if it would have worked.

I tried implementing ICorsPolicyProvider creating a custom CORS attribute but this seems to be a dead end since I can't find a way to inject the services I need to verify the origin.

Is there a way to verify the Origin-header while having access to needed services?

1

There are 1 best solutions below

0
On BEST ANSWER

The solution is to implement ICorsService. The default implementation (CorsService) is easy to understand and is a good starting point.

In your services configuration, replace the call

services.AddCors();

with:

services.AddTransient<ICorsService, YourImplementationOfICorsService>() .AddTransient<ICorsPolicyProvider, DefaultCorsPolicyProvider>();

Everything else is the same. The only drawback of this solution is that no scoped dependencies may be injected into your ICorsService implementation.