Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net core2 CORS - How SetIsOriginAllowed works?

Want to allow my API to be accessed from different sites. For this had:

services
    .AddCors(options =>
    {
        options.AddPolicy(PolicyName, builder =>
        {
            builder
                .SetIsOriginAllowedToAllowWildcardSubdomains()
                .WithOrigins(
                    "http://*.my-api.com",
                    "http://*.my-api.service"
                )
...

This doesn't seem to allow httpS or when I specify the port in the request.

Ex.: https://www.my-api.com:3000

Thought could replace the WithOrigins with SetIsOriginAllowed()

services
    .AddCors(options =>
    {
        options.AddPolicy(PolicyName, builder =>
        {
            builder
                .SetIsOriginAllowed(IsOriginAllowed)

where IsOriginAllowed function is defined as:

private static bool IsOriginAllowed(string host)
{
    var corsOriginAllowed = new[] { "my-api.com", "my-api.service" };

    return corsOriginAllowed.Any(origin =>
        Regex.IsMatch(host, $@"^http(s)?://.*{origin}(:[0-9]+)?$", RegexOptions.IgnoreCase));
}

but this doesn't work at all, even the regular expression is returning true when I want.

Does anyone know why this doesn't work and can show me the right way to allow httpS (besides duplicating all the domains in WithOrigins() with httpS and different ports.

Thanks

like image 347
Riga Avatar asked Dec 15 '17 17:12

Riga


People also ask

What is SetIsOriginAllowed?

SetIsOriginAllowed() method returns true if an origin is allowed, so always returning true allows any origin to send requests to the api.

How do I allow all CORS in net core?

There are three ways to enable CORS: In middleware using a named policy or default policy. Using endpoint routing. With the [EnableCors] attribute.


1 Answers

SetIsOriginAllowed() does work. Was testing with Postman and as was told, Postman doesn't care about headers returned from the server. It's the browser who enforces the Cors headers.

To test properly created a little html page under a test site with below javascript

<html>
    <script>
        fetch('http://test.com:5000/v2/campaign/hallo3').then(function(response) {
            return response.json();
        }).then(function(j) {            
	        alert(JSON.stringify(j));
        });
    </script>
</html>

when domain is NOT included in the Cors allowed list browser doesn't display the returned values from API

Domain not allowed

After adding test domain to allowed domains list browser display the data and get the content Cors headers

enter image description here

Another problem was that with just the SetIsOriginAllowed() server was not sending the 'Vary' header. Had to set both:

.SetIsOriginAllowed(IsOriginAllowed)
.WithOrigins(corsOriginAllowed)
like image 82
Riga Avatar answered Sep 28 '22 20:09

Riga