GithubHelp home page GithubHelp logo

aspnet / cors Goto Github PK

View Code? Open in Web Editor NEW
90.0 90.0 47.0 654 KB

[Archived] Implementations of common CORS policy and CORS middleware. Project moved to https://github.com/aspnet/AspNetCore

License: Apache License 2.0

Shell 5.01% C# 84.56% Batchfile 0.28% PowerShell 3.60% Groovy 0.66% JavaScript 5.88%
aspnet-product

cors's Introduction

CORS [Archived]

This GitHub project has been archived. Ongoing development on this project can be found in https://github.com/aspnet/AspNetCore.

CORS repository includes the core implementation for CORS policy, utilized by the CORS middleware and MVC.

This project is part of ASP.NET Core. You can find samples, documentation and getting started instructions for ASP.NET Core at the AspNetCore repo.

cors's People

Contributors

ajaybhargavb avatar aspnetci avatar brennanconroy avatar chengtian avatar davidfowl avatar dougbu avatar eilon avatar haok avatar harshgmsft avatar henkmollema avatar hishamco avatar javiercn avatar jbagga avatar jkotalik avatar juntaoluo avatar kichalla avatar kirthik avatar luckywraptor avatar michielpost avatar mikeharder avatar natemcmaster avatar norgerman avatar ntaylormullen avatar pakrym avatar pranavkm avatar priyanshu92 avatar ryanbrandenburg avatar sindhudweep avatar tratcher avatar troydai avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cors's Issues

Not Understanding CORS

I've configured and enabled CORS in my Startup. Yet when I run my test application not one single static file includes the headers. Chrome continues to post errors about it, but IE is just happy.

Is there something I'm not understanding?

Access-Control-Allow-Headers shows as two separate headers which makes IE not process a cors response.

Moving the bug from dotnet/aspnetcore#640
@esyorcho
I've been trying to "tie" both headers together (authentication and content-type), so that they show up in one line like:

Access-Control-Allow-Headers: content-type, authorization

But no matter what I did, they were being separated in 2 lines. I removed the authorization header from my first call (the login) since I didn't need it anyways, and then it went through (because it only had the content-type header). Somehow post calls within the application that need the authorization header still have the same problem (content-type missing, because it's in the second line and IE can't read it). Could you please tell me if there's a way that you know to make both headers show up in one line? At the moment we're adding the Authorization header this way in js:

            // add authentication header:
            var authHeader = "";//"basic ";
            authHeader += this.get("token") ? JSON.stringify(this.get("token")) : null;
            return {
                headers: _.extend(headers, { Authorization: authHeader })
            };

and we do our post calls with restangular this way:

RestangularFactory.all("search/getFields").post(criteria, "");

In our server api we have all post and get calls with:

[Produces("application/json")]
[HttpPost]
public string GetFields([FromBody]CriteriaInputData criteria)
{
    return ...
}

If there is any other information that you need please let me know

Thank you very much

Cors requires authorization on preflight

From @shederman on January 8, 2016 7:11

The W3 spec clearly states that this should not be the case.

Request:
Request URL:http://localhost:2116/releases
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:[::1]:2116
Response Headers
view source
Content-Length:0
Date:Fri, 08 Jan 2016 06:56:49 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcUHJvamVjdHNcT2N1bHVzXHNyY1xPY3VsdXMuUmVsZWFzZS5BcGlcd3d3cm9vdFxyZWxlYXNlcw==?=
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:GET
Cache-Control:max-age=0
Connection:keep-alive
Host:localhost:2116
Origin:http://localhost:17185
Referer:http://localhost:17185/rel
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36

Copied from original issue: aspnet/Security#648

Security Issue: CORS Mvc auth filter still allows request to execute.

As things stand, if EnableCorsAttribute is used on an MVC action method, the method will still execute and spit out a result over the socket regardless of the CORS test result. The combat this security hole, I had to write an action filter that checks for the Origin header and see that whenever that header exists in the request, I short circuit the response with a negative status code whenever the CORS authorization filter does not include Access-Control-Allow-Origin with the requesting origin as part of the outgoing response headers. Please fix this, or make it clear in the docs that a filter like the one I am using must be included in the MVC filter pipeline to avoid leaking data in failed CORS requests.

Update CORS package version

Microsoft.AspNet.Cors is an existing package that we shipped for Katana. We should either update the version of the new functionality to 6.0.0 or use a different package ID.

CORS does not works after enable JWT bearer token

I use JWT bearer token in my web api project and the codes like this:

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    Authority = appSettings.Value.IdentityServerUrl,
    RequireHttpsMetadata = false,
    AutomaticAuthenticate = true
});

And the CROS settings like this:

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins", policyBuilder =>
                {
                    policyBuilder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
            });
            app.UseCors("AllowAllOrigins");

The requests:
image
image

Why the response of first OPTION request contains Access-Control-Allow-Origin:*
But the second GET request does not contain Access-Control-Allow-Origin:* ?

I use angularjs to call the API:

  function authInterceptorService($q, $location, $injector, config, localStorageService, _) {
      var service = {
        responseError: _responseError,
        request: _request,
      };

      var apiUrl = config.API_URL;

      return service;
      /////////////

      function _request(config) {
        var access_token = localStorageService.get('access_token');

        config.headers = config.headers || {};
        if (access_token && _.startsWith(config.url, apiUrl) && (!_.startsWith(config.url, apiUrl+'/token') || !_.startsWith(config.url, apiUrl+'/sendcode'))) {
          config.headers.Authorization = 'Bearer '+ access_token;
        }

        return config;
      }

If not set the authorization header, the same request like this:
image

API review updates for CORS

In particular, a lot of types need to move out of the Cors.Core namespace. The main Cors namespace should have the most commonly used types, and plumbing can go into a sub-namespace.

CORS header comparisons should be case-insensitive

Per the spec:

http://www.w3.org/TR/cors/#terminology

A header is said to be a simple header if the header field name is an ASCII case-insensitive match for Accept, Accept-Language, or Content-Language or if it is an ASCII case-insensitive match for Content-Type and the header field value media type (excluding parameters) is an ASCII case-insensitive match for application/x-www-form-urlencoded, multipart/form-data, or text/plain.

Improved options for adding policies

I'd love to be able to have the Cors middleware resolve my policies from the container. If any of my policies require configuration parameters, it seems like there's no nice clean way to break them out into their own files that can depend on IOptions<Something>.

Alternatively, it might be nice if I could better leverage the options system to set up my CorsOptions instance.

The current setup seems to force me to either move lots of definitions to an extension method, or I end up having to leave them inside of my Startup.cs, which obviously gets quite big.

Cannot find documentation/examples of how to support wildcard subdomains

Below is what i have posted on stackoverflow regarding this issue...

I have cors setup correctly in an ASP.NET Core web app. Im using the following package...

"Microsoft.AspNet.Cors": "6.0.0-rc1-final"

and here is the startup.cs snippet...

public virtual IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddCors
    (
        options =>
        {
            options.AddPolicy
            (
                CORSDefaults.PolicyName, 
                builder =>
                {
                    //From config...
                    var allowedDomains = new []{"http://aaa.somewhere.com","https://aaa.somewhere.com","http://bbb.somewhere.com","https://bbb.somewhere.com"};

                    //Load it
                    builder
                        .WithOrigins(allowedDomains)
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                }
            );
        }
    );
}

This works great except that the list of subdomains to allow is growing fast and I want to allow all subdomains of "somewhere.com". Something like "*.somewhere.com". I cant seem to find any documentation on how to do this in the new ASP.NET Core (MVC6, ASP.NET5, VNext). All the docs/examples I'm finding that demonstrate how to do this are for earlier versions of MVC or WebApi. How can I achieve this in the new stack?

CORS rc1-final - Not working

My CORS configuration no longer appears to work in rc1-final. None of my responses are including the headers for ACCESS-CONTROL.

Did something change in rc1-final?

CORS on Azure WebApp

When I use CORS in a WebApp Azure, this is ignored.
The only thing that takes is a Web.config in "wwwroot".
Am I doing here an error or is this a bug?

ConfigureServices

            services
                .AddMvcCore()
                .AddViews()
                .AddCors(options =>
                {
                    options.AddPolicy("Default", builder =>
                    {
                        builder.AllowAnyHeader();
                        builder.AllowAnyMethod();
                        builder.AllowCredentials();

                        builder.WithOrigins("myapp.azurewebsites.net");                   
                    });
                })
                .AddJsonFormatters(j => j.ContractResolver = new CamelCasePropertyNamesContractResolver());

Configure

app.UseCors("Default");
app.UseMvc();

CORS stop working after app restart in Azure web

Maybe this is related to asp.net 5 core and not to cors middleware but I with UseCors() and [EnableCors] options used CORS is working fine only temporarily. On Azure (probably after app restart) cors policy settings disappear and I can't access service from other domain (No 'Access-Control-Allow-Origin' header is present on the requested resource).

Here is my configuration (UseCors is placed after UseMvc).

public void ConfigureServices(IServiceCollection services)
        {
            configureCors(services);
            services.AddMvc(options =>
            {
                options.Filters.Add(new ErrorFilter());
            });

        }


        private static void configureCors(IServiceCollection services)
        {
            services.AddCors();

            services.ConfigureCors(x => x.AddPolicy("allowAll", p=>p.AllowAnyOrigin().
            AllowAnyHeader().AllowAnyMethod().AllowCredentials()));
        }

        public void Configure(IApplicationBuilder app, IApplicationEnvironment env,  ILoggerFactory loggerFactory)
        {
            ConfigureOAuthTokenConsumption(app);

            app.UseMiddleware<StaticFileMiddleware>(new StaticFileOptions());
            app.UseErrorPage();

            app.UseMvc();

            app.UseCors("allowAll");

        }

[UPDATE]
Everything works fine when I removed UseCors() from the Startup.cs but kept the Attribute.
So when both options are in place we might have strange behavior when Cors works normally only in the beginning.

Unable to resolve service for type 'Microsoft.AspNet.Cors.Core.ICorsService' while attempting to activate 'Microsoft.AspNet.Cors.CorsMiddleware'.

I'm trying to use the middleware but I'm getting the following exception.

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNet.Cors.Core.ICorsService' while attempting to activate 'Microsoft.AspNet.Cors.CorsMiddleware'.
   at Microsoft.Framework.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
   at Microsoft.Framework.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
   at Microsoft.AspNet.Builder.UseMiddlewareExtensions.<>c__DisplayClass2_0.<UseMiddleware>b__0(RequestDelegate next)
   at Microsoft.AspNet.Builder.Internal.ApplicationBuilder.Build()
   at Microsoft.AspNet.Hosting.Internal.HostingEngine.Start()
   at Microsoft.AspNet.Hosting.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
   at Microsoft.Framework.ApplicationHost.Program.ExecuteMain(DefaultHost host, String applicationName, String[] args)
   at Microsoft.Framework.ApplicationHost.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
   at dnx.host.Bootstrapper.RunAsync(List`1 args, IRuntimeEnvironment env, FrameworkName targetFramework)
   at dnx.host.RuntimeBootstrapper.ExecuteAsync(String[] args, FrameworkName targetFramework)
   at dnx.host.RuntimeBootstrapper.Execute(String[] args, FrameworkName targetFramework)

Here is the code I'm using.
Note that I've tried multiple variations but nothing worked, I got the same exception.

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigureCors(co => co.AddPolicy("AllowAll", cp => cp.AllowAnyOrigin()));
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseFileServer(new FileServerOptions()
            {
                EnableDefaultFiles = true,
                EnableDirectoryBrowsing = true
            });

            app.UseCors("AllowAll");
        }
    }

Finally here is the project file.

{
    "webroot": "cdnroot",

    "dependencies": {
        "Microsoft.AspNet.Server.IIS": "1.0.0-beta6",
        "Microsoft.AspNet.Server.WebListener": "1.0.0-beta6",
        "Microsoft.AspNet.StaticFiles": "1.0.0-beta6",
        "Microsoft.AspNet.Cors": "1.0.0-beta6"
    },

    "commands": {
        "web": "Microsoft.AspNet.Hosting --config hosting.ini"
    },

    "frameworks": {
        "dnxcore50": { }
    },

    "publishExclude": [
        "node_modules",
        "bower_components",
        "**.xproj",
        "**.user",
        "**.vspscc"
    ],
    "exclude": [
        "cdnroot",
        "node_modules",
        "bower_components"
    ]
}

GET and POST method is always enabled for CORS?

Create a simple MVC web app with the following code

services.ConfigureCors(options =>
{
    options.AddPolicy(
        "AllowMyMethodRequest",
        builder =>
        {
            builder.AllowAnyOrigin()
                    .WithMethods("MYMETHOD");
        });
}

as the only CORS-related configuration.
Then apply [EnableCors("AllowMyMethodRequest")] to an action in your controller and try accessing view of that action. Here are the methods I used and corresponding results:
(1) GET: succeeds (why?)
(2) POST: succeeds (why?)
(3) HEAD: fails (expected)
(4) MYMETHOD: succeeds (expected)

CorsMiddleware should resolve dependencies dynamically

The dependency on ICorsService and ICorsPolicyProvider to the ctor for the middleware means the use of these services are in effect singletons. This means implementations that require scoping in DI (e.g. to hit a database) will not work properly and the one instance will be used concurrently. I'd suggest a change in Invoke to resolve these dynamically.

CORS is not enabled when there is any error occured

I enabled the CORS support using Microsoft.AspNet.Cors.Core(6.0.0-beta8) and Microsoft.AspNet.Cors (6.0.0-rc1-final) in a ASP.NET 5 RC1 project.

It is ok when the api called succeeded.

But when I use JWT bearer middleware and provided a invalid token, the middleware throw an 500 error, then the CORS is not enabled, no Access-Control-Allow-Origin in the HTTP headers. Can you help how to add the CORS when there is any error occurred? Thanks.

Missing Vary: Origin header for multiple allowed origins

Currently VaryByOrigin is set to true only when AllowAnyOrigin and SupportCredentials is true. It should also be set when multiple origins are configured/allowed. See spec for more details.

Resources that wish to enable themselves to be shared with multiple Origins but do not respond uniformly with "*" must in practice generate the Access-Control-Allow-Origin header dynamically in response to every request they wish to allow. As a consequence, authors of such resources should send a Vary: Origin HTTP header or provide other appropriate control directives to prevent caching of such responses, which may be inaccurate if re-used across-origins.

OPTIONS requests receiving 404 when routes have HTTP method constraints

My Startup.cs contains the following:

            services.AddCors(options => options
                .AddPolicy("TrustedHosts", builder => builder
                    .AllowCredentials()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithOrigins(Configuration.TrustedHosts().ToArray())));

I have my own tools for registering routes, however I've noticed an interesting/odd behaviour when using controller annotation for CORS. I believe it boils down to this:

if (httpMethod != null)
    constraints.Add("httpMethod", new HttpMethodRouteConstraint(httpMethod));

What I think is happening is the preflight only works when I remove any HTTP method constraint from the route.

I'm not sure if that's just a limitation of using annotations, in which case I might see about providing a way to register CORS policies against routes in my utilities. But this is definitely a strange and unexpected side effect of using the controller annotations.

No CORS headers sent in case of error 500

There is a similar closed issue that I have commented on, but there hasn't been any response, so I created a new issue.
Closed issue: #46

Comment copy:

Has this issue been revisited?
I mean, is it really a CORS policies job to prevent sending out full exception details?

But the main problem for me is that if I allow some domain do make CORS requests, I expect them to get all the information.

If the request was made with "XMLHttpRequest" as fallows:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.status); // with no CORS headers allways 0
if(this.status === 500){
// make some noise
}
};
xhttp.open("GET", 'http://www.example.ee/api', true);
xhttp.send();

If the response is indeed 500 but without CORS headers, then the "XMLHttpRequest" status will be 0, not 500.

So what's your ideas on this? Or am I missing something?

SimpleRequestHeaders present in Access-Control-Request-Headers are filtered out of response

Title

SimpleRequestHeaders present in Access-Control-Request-Headers are filtered out of response's Access-Control-Allow-Headers

Functional impact

MS Edge includes 'accept' within a CORS preflight request. When the preflight response does not include 'accept', Edge will stop the real request.

Minimal repro steps

This unit test demonstrates the behavior I'm talking about.

Expected result

When a preflight request is made, the response should contain all headers in the request which are allowed by the CORS policy, not just custom ones.

Actual result

Some specific headers are being filtered out of the response.

Further technical details

The filter in question.

Not working?

Hi,

Using a newly generated RC1 project from visual studio, adding Cors as described by the oficial documentation (https://docs.asp.net/en/latest/security/cors.html) seems to not work.

project.json (all of it):
{
"version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true
},

"dependencies": {
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
"Microsoft.AspNet.Cors": "6.0.0-rc1-final"
},

"commands": {
"web": "Microsoft.AspNet.Server.Kestrel"
},

"frameworks": {
"dnx451": { },
"dnxcore50": { }
},

"exclude": [
"wwwroot",
"node_modules"
],
"publishExclude": [
".user",
"
.vspscc"
]
}

Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddCors();
services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseIISPlatformHandler();

app.UseStaticFiles();

app.UseCors(builder =>
    builder
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowAnyOrigin()

);

app.UseMvc();

}

Outputs the following headers:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Kestrel
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcQXhlbE1cRGVza3RvcFxXZWJBcHBsaWNhdGlvbjFcc3JjXFdlYkFwcGxpY2F0aW9uMVx3d3dyb290XGFwaVx2YWx1ZXM=?=
X-Powered-By: ASP.NET
Date: Tue, 01 Mar 2016 07:17:50 GMT
Content-Length: 19

Resource sent to unauthorized origin

Hi,
I´ve noticed that in a MVC 6 app, using CORS, when a request is made from a unauthorized origin, the header "Access-Control-Allow-Origin" is, as expected, not set, but the response status code 200 and the resource is sent in the response body. I was wondering, that if the resource cannot be shared, it should not be sent across the wire. I was expecting that the request would not event hit the Controller.

Is this behavior correct?

Thank you

No CORS headers sent in case of error 500

When the controller throws an exception, which results in an error 500, the CORS headers are not sent.

Is that by design? If so, why? If not, that's probably a bug.

Middleware doesn't return required headers

These headers are never returned:
Access-Control-Allow-Methods
Access-Control-Max-Age

and the status code is 204, and should be 200 (debatable, but it seems like everyone is returning 200 since technically OPTIONS should return a list of allowed methods)

CORS middleware doesn't work if placed after MVC

If you load CORS after MVC middleware, it's not working.
Here is my Startup.cs code:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.ConfigureCors(options => options.AddPolicy("allowAll", p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseStaticFiles();
        app.UseMvc();
        app.UseCors("allowAll");
    }

if I load it like this:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseStaticFiles();
        app.UseCors("allowAll");
        app.UseMvc();
    }

it works!

Attribute doesn't work with UseCors

Create two policies, useCors on one, and add attributes to controllers for the other. The attributes won't trigger. A 204 is returned instead. Adding in an Options method with an attribute on the controller or the actual verb (GET, HEAD, etc...) returns a 200 and the correct headers.

Using this setup:

services.AddCors(o =>
{
    o.AddPolicy("AllowAll", builder =>
    {
        builder.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod();
    });
    o.AddPolicy("OtherPolicy", builder =>
    {
        builder
            .AllowAnyHeader()
            .AllowAnyMethod()
            .WithOrigins("https://my.special.site.com");
    });
});
OPTIONS /v1/route/1 HTTP/1.1
    Host: localhost:5001
    Connection: keep-alive
    Pragma: no-cache
    Cache-Control: no-cache
    Access-Control-Request-Method: GET
    Origin: http://localhost:8080
    User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36
    Access-Control-Request-Headers: accept, authorization
    Accept: */*
    DNT: 1
    Referer: http://localhost:8080/
    Accept-Encoding: gzip, deflate, sdch

returns:

HTTP/1.1 204 No Content
    Date: Sat, 29 Oct 2016 15:55:39 GMT
    Server: Kestrel
    X-XSS-Protection: 1; mode=block
    Strict-Transport-Security: max-age=31536000
    X-Content-Type-Options: reflected-xss block

Instead of:

HTTP/1.1 200 OK
    Date: Sat, 29 Oct 2016 15:56:40 GMT
    Content-Length: 0
    Server: Kestrel
    Access-Control-Allow-Headers: authorization
    Access-Control-Allow-Origin: *
    X-XSS-Protection: 1; mode=block
    Strict-Transport-Security: max-age=31536000
    X-Content-Type-Options: reflected-xss block

By simply removing the use of UseCors("OtherPolicy") and only using the attribute [EnableCors("AllowAll")] this works as intended.

Missing CorsMiddleware

After upgrading a project to beta6 and installing the Microsoft.AspNet.Cors.Core 1.0.0-beta6 package, there is no longer the 'UseCors' extension for using the 'CorsMiddleware' component. 'ConfigureCors' and 'AddCors' still exist, but not 'UseCors'. I assumed this was removed, but after downloading the CORS beta6 release from GitHub, those components seem to still exist.

Chrome treats any non-200 responses to preflight requests as a failure

From @sandorfr (originally filed as aspnet/Mvc#2542)

Looks like the current implementation of cors return a 204 for preflight request and it looks like Chrome considers any non-200 being a failure. Doing some quick research on the web I've seen that there is discussions about what should be the good behavior but what I'm sure of is that we need that to just work. Maybe we should be able to configure it?

Preflight request seems to require authentication (beta7)

It appears that preflight requests require authentication. I'm currently using the bearer token middleware. Chrome does not provide the credentials when issuing preflight request but if I don't provide the authorization header, the preflight (OPTIONS) fails with 401. ( I tried with and without AutomaticAuthentication).

So I guess this is a configuration issue. I tried to move AddCors to the very beginning of ConfigureServices and played with (Dis)AllowCredentials without any luck.

 services.AddCors();
            services.ConfigureCors(options =>
            {
                options.AddPolicy("api", builder => builder
                .AllowAnyOrigin()
                //.AllowAnyHeader()
                .WithHeaders("accept", "accept-encoding", "accept-language", "X-Requested-With", "authorization", "applicationToken", "content-type", "time-zone-offset", "api-version")
                .WithMethods("GET", "PATCH", "PUT", "DELETE", "POST")
                .WithExposedHeaders("new-authentication-token"));
            });

CORS only works with policy.WithOrigins("*");

I tried the CORS middleware on DNX Beta 4 / Ubuntu / Kestrel and I registered CORS in ConfigureServices:
services.AddCors();

And in Configure I configured it - when using this, it works from my Angular App:

app.UseCors(policy => {
                policy.WithOrigins("*"); 
                policy.AllowAnyHeader();
                policy.AllowAnyMethod();
});

But the following doesn't work:

app.UseCors(policy => {
                policy.AllowAnyOrigin();
                policy.AllowAnyHeader();
                policy.AllowAnyMethod();
});

I'm I doing something wrong?

Preflight requests

Preflight requests don't seem to work (tried with beta5 and beta6).
I have a project that uses CORS and MVC with the following Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.ConfigureCors(options =>
        {
            options.AddPolicy("AllowAll",
                builder =>
                {
                    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                });
        });
        services.AddCors();
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseStaticFiles();
        app.UseMvc();
    }

I decorated my controller with [EnableCors("AllowAll")]

I can perform simple requests with no issues however when a preflight request is involved the response lacks Access-Control-Allow-Origin, Access-Control-Allow-Method and Access-Control-Allow-Headers

This is the preflight request:

OPTIONS http://localhost:17477/api/Restaurant HTTP/1.1
Host: localhost:17477
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Origin: http://run.plnkr.co
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

And the response:

HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Server: Microsoft-IIS/10.0
Public: OPTIONS, TRACE, GET, HEAD, POST
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcZnJhbmNvaXMubmd1eWVuXFNvdXJjZVxSZXBvc1xQcm9qZWN0QnJhaVxzcmNcRGVsaWV2cnlBUElcd3d3cm9vdFxhcGlcUmVzdGF1cmFudA==?=
X-Powered-By: ASP.NET
Date: Fri, 31 Jul 2015 12:01:14 GMT
Content-Length: 0

The preflight request happens because the Content-Type is application/json

Cors does not appear if the application crash

When your application crash (500 Internal Error), cors response header are not present.

I think it should because the error on the front is therefore misleading.

request headers:

Accept:/
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-GB,en;q=0.8,en-US;q=0.6,fr;q=0.4
Connection:keep-alive
Host:localhost:5000
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
X-FirePHP-Version:0.0.6

response headers :

Content-Type:text/html; charset=utf-8
Date:Fri, 02 Sep 2016 15:03:12 GMT
Server:Kestrel
Transfer-Encoding:chunked

Cors is active and works for successful requests.

beta8: Using string[] to add policy at startup.

I am trying to take advantage of the config.json, config.Development.json, and config.Production.json to manage the allowed CORS origins for a set of services.

In my startup function I read in the config.{env.EnvironmentName}.json that is in the Properties > launchSettings.json file. In this case I have the ASPNET_ENV environment variable set to "Development".


        public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
        {
            // Setup configuration sources.
            var builder = new ConfigurationBuilder()
                .SetBasePath(appEnv.ApplicationBasePath)
                .AddJsonFile("config.json")
                .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

lanchSettings.json snippet...


    "web": {
      "commandName": "web",
      "environmentVariables": {
        "ASPNET_ENV": "Development"
      }
    }

In my configuration files I have a collection of clients I want to allow. I am showing what I have in my config.Development.json for example.


{
    "ClientUrls": {
      "Portal": "http://localhost:5000/"
      "Manager": "http://localhost:4000/"
    }
}

So based upon what I have I should be able to add both of these to my accepted CORS origins. It is a bit cumbersome and maybe there is a better way to do it but here is what I have and it doesn't work... I would expect this to work since the function parameter is a string[] and that is what I am providing.


        public void ConfigureServices(IServiceCollection services)
        {
            List<string> clients = new List<string>();
            clients.Add( Configuration["ClientUrls:Portal"] );
            clients.Add( Configuration["ClientUrls:Manager"] );

            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.WithOrigins(clients.ToArray()));
            });
        }

This does work...


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.WithOrigins("http://localhost:5000/", "http://localhost:4000/"));
            });
        }

If there is a better way to provide a configurable set of allowed origins based upon the environment that I am running under, I am interested in understanding the alternative approach. The issue is that either way I would expect the List<string>().ToArray() to work as the parameter since the result is a string[].

Allow a more flexible AllowOrigin response

Instead of the CorsService peeking into the CorsPolicy

   policy.Origins.Contains(origin)

A method OriginAllowed(string origin) would allow for a much more flexible lookup policy. The service would then call:

  policy.OriginAllowed(origin)

This allows the policy to respond with a more ad hoc response like a (database) lookup.
The default would simply be:

        public virtual bool OriginAllowed(string origin)
        {
            return this.Origins.Contains(origin);
        }

But an override policy could become something like:

        public override bool OriginAllowed(string origin)
        {
            return repository.Exists<Sites>(s => s.Origin == origin);
        }

Session is not working on IIS with CORS

From @devilsuraj on June 28, 2016 8:19

I am using sessions to manage application state in ASP.NET CORE and it's configured as below.

 services.AddSession(options =>
            {
                options.CookieName = ".my.Session";
                options.IdleTimeout = TimeSpan.FromSeconds(20);
            });

It's working on localhost but on remote IIS 8 it's not creating cookies so not able to get the values. I also have enabled CORS and don't know what exactly caused this problem. In log it's not showing error either. It's creating session getting stored id but no cookie at client side.

Copied from original issue: aspnet/Session#118

Cors needs logging

CORS really badly needs some logging - this is an area of frequent question-asking. We should try to automate our question answering.

Ideas:

  • Whether or not request was preflight (debug)
  • Where or not request had origin header (debug)
  • Policy success or failure with failure reason (info)

CORS policy.WithOrigins("...") does not work?

Apparently the method AllowAnyOrigin() works fine adding the "Access-Control-Allow-Origin: * " header to the response.

allowanyorigin

But what's going on with WithOrigins("..."), It does not add the "Access-Control-Allow-Origin: ... " header to the response.

withorigins

Shouldn't it add something like...

  "Access-Control-Allow-Origin: http://addeddorigin.com/ "

?

My code:

services.ConfigureCors( config => config.AddPolicy("AddSingle",
                policy => policy
                    .WithOrigins("http://localhost:9000/")
                    .AllowAnyMethod() 
            ));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.