Git Product home page Git Product logo

nelmiocorsbundle's Introduction

NelmioCorsBundle

About

The NelmioCorsBundle allows you to send Cross-Origin Resource Sharing headers with ACL-style per-URL configuration.

Features

  • Handles CORS preflight OPTIONS requests
  • Adds CORS headers to your responses
  • Configured at the PHP/application level. This is convenient but it also means that any request serving static files and not going through Symfony will not have the CORS headers added, so if you need to serve CORS for static files you probably should rather configure these headers in your web server

Installation

Require the nelmio/cors-bundle package in your composer.json and update your dependencies:

composer require nelmio/cors-bundle

The bundle should be automatically enabled by Symfony Flex. If you don't use Flex, you'll need to enable it manually as explained in the docs.

Usage

See the documentation for usage instructions.

License

Released under the MIT License, see LICENSE.

nelmiocorsbundle's People

Contributors

4c0n avatar chris53897 avatar dunglas avatar gwendolenlynch avatar javiereguiluz avatar kocal avatar leevigraham avatar leofeyer avatar luispabon avatar lyrixx avatar mdeboer avatar meyerbaptiste avatar michalbundyra avatar mkopinsky avatar mweimerskirch avatar nocive avatar nyholm avatar oliboy50 avatar oskarstark avatar phansys avatar prosalov avatar seldaek avatar simonharris avatar simonsimcity avatar smatyas avatar sroze avatar tacman avatar toflar avatar vincent-chapron avatar vincentchalamon 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  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

nelmiocorsbundle's Issues

Contribution offering: abstracted CORS configuration providers

Contributed as #15

We are currently implementing CORS support into our REST API at http://github.com/ezsystems/ezpublish-kernel.

As it turns out, this bundle really does what needs to be done, and it does it well. We have a partially working implementation, but I'm thinking that I'd like to use NelmioCorsBundle instead of writing our own thing.

But the thing is: we need to make some stuff dynamic (methods list per URI, etc).

I was thinking that we could propose support for some cors_request_matcher service tag. Those services would provide a couple methods used to check a CORS request. A default one would be implemented that uses the bundle's semantical configuration as a source.

What do you think ? Would you be willing to accept such a contribution.

NB: there is also a need for a security request matcher in order to ignore auth on preflight requests. We should be able to contribute that as well.

No 'Access-Control-Allow-Origin' header is present on the requested resource.

My Symfony API, I used FOSRestBundle worked ok and suddently I have a CORS error on every request form my Vue.js frontend

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://rvpfront.dev:8080' is therefore not allowed access.

My Nelmio Configuration is the following

# Nelmio Cors Bundle
nelmio_cors:
    defaults:
        allow_credentials: true
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
    paths:
        '^/':
            allow_origin: ['*']
            allow_headers: ['origin', 'content-type', 'Authorization']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE','OPTIONS']
            max_age: 3600

I'm really confused, it worked on friday and for 3 weeks before that.

Make sure simple headers are always valid

The spec states that Accept, Accept-Language, Content-Language are simple headers, as such they must not be listed in the preflight request, but they sometimes (chrome) are, so they should always be accepted even if not listed in the configuration.

Allow all subdomains of current domain only

When I use ['*'] everything works great but I want to allow only main domain and all of (wildcard) subdomains to access api. Something like this:

allow_origin: ['CURRENT_DOMAIN', '*.CURRENT_DOMAIN']

Any ideas?

Composer post-update-cmd error

After upgrading to the latest version 1.5.2, the following error appears and the composer fails during post-install-cmd

[Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException]
The service "nelmio_cors.options_provider.config" has a dependency on a non-existent parameter "nelmio_cors.map".

Script Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache handling the post-update-cmd event terminated with an exception

[RuntimeException]
An error occurred when executing the "'cache:clear --no-warmup'" command:

[Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException]                                         
The service "nelmio_cors.options_provider.config" has a dependency on a non-existent parameter "nelmio_cors.map".    

Downgrading to 1.5.1 seems to fix the issue. Any thoughts?

Caching preflight requests reponses

Hello!

First: Thank you for this amazing bundle :).

I noticed that the bundle did not detect that:
When i call my url like that: http://api.domain.com/component/{parameter} twice, the second OPTIONS call done by my browser is cached, but when i change the value of my parameter, the bundle detects it like a change of route, which is not incorrect but is really annoying because it slows the final response time...

I was wondering if there is a way to cache response of Preflight requests when the route has a parameter in it: http://api.domain.com/component/{parameter}

I hope i didn't miss something.

Thank you,
Hicham.

No 'Access-Control-Allow-Origin' with If-Modified-Since and Chrome

Hi, thanks very much for this bundle! Has been really helpful getting an AngularJS client (mostly) working with Symfony. However I'm hitting an issue that seems to be specific to mod time request/response headers, specific to Chrome (Firefox works) and possibly specific to Angular. I've tried adding various logging in CorsListener but can't work it out.

The plan was to avoid sending duplicate data by having my Angular client set If-Modified-Since headers (it knows when it cached the data last) and having the Symfony controller return a 304 if there's no newer data.

The symptoms are very similar to #25 though I'm not using FOSRestBundle - Chrome says:

XMLHttpRequest cannot load http://[myapp].localhost/app_dev.php/api/endpoint/123. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[myapp].localhost:8100' is therefore not allowed access.

This happens consistently on one particular API call from Chrome. However the same thing works in Firefox (I see an OPTIONS followed by a GET), and calls that aren't expected to return 304 Unmodified work in Chrome too. This request has credentials (a cookie), but so do others that work.

In this particular response I'm trying to use $response->isNotModified($request); from my controller to return a 304. This is meant to update the status code, remove any disallowed headers (I haven't yet spotted any of these which should break the requests) and remove the response body.

I've also tried variants like manually setting the status code or manually calling setNotModified() when appropriate, but these fail in the same way.

setLastModified() adds that header without issues when added to a regular 200 response (but this doesn't do anything useful for me).

In trying to debug this it appeared that CorsListener might never actually get an OPTIONS request from these calls, though it does from the Firefox equivalent of the same call, and other calls that don't have use If-Modified-Since and a 304.

Happy to provide any more details or try logging different things if you have any ideas!

Allow all headers - or disable allow_headers check

I think it would make sense to allow the ability to skip the allow_headers check. We could have a
allow_headers = ['*'] or if allow_headers is an empty array, then skip the check.

This way we don't have to add each header to the list. Does it make sense?

XMLHttpRequest cannot load, Origin not allowed

Hi,

First, thanks for this wonderful bundle. I've got a problem when using it on my project, i have this error :

XMLHttpRequest cannot load http://www.website1.com/public-api/v1/tag/stat. Origin http://www.website2.com is not allowed by Access-Control-Allow-Origin.

My config.yml :

nelmio_cors:
    defaults:
        allow_credentials: true
        allow_origin: ['*']
        allow_headers: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept']
        allow_methods: ['POST','GET','DELETE','PUT']
        expose_headers: ['*']
        max_age: 0
    paths:
      '^/public-api':
          allow_credentials: true
          allow_origin: ['*']
          allow_headers: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept']
          allow_methods: ['POST','GET','DELETE','PUT']
          expose_headers: ['*']
          max_age: 0

I try '^/public-api' or '^/public-api/', same error.

I also try to enable the bundle on the root with this config, it's work :

nelmio_cors:
    defaults:
        allow_credentials: true
        allow_origin: ['*']
        allow_headers: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept']
        allow_methods: ['POST','GET','DELETE','PUT']
        expose_headers: ['*']
        max_age: 0
    paths:
      '^/': ~

I don't want to enable it on the entire project, how can i do ? Thanks.

Add a security-note to the documentation for method-overloading

I don't know if that's much of an issue, but the administrator should at least have it in mind:

If the administrator allows the method POST, and method-overloading is enabled, he basically allows all other methods as well! - At least for users, knowing of this feature.

Add Symfony related GitHub topics

Now that Github introduced the topics feature for all repositories, Symfony proposed in this blog post to standardize some tags for all Symfony related repositories to make easier to discover them. The official recommendation is to add php, symfony, bundle and symfony-bundle topics and then, your own specific topics.

Headers aren't added if firewall denies request

If one of the firewalls denies the request, those headers aren't added ... Sorry, but can't use it at this state in my application ...

The system throws the exception AuthenticationCredentialsNotFoundException "A Token was not found in the SecurityContext."

custom headers

Hi.

I'm having a problem trying to pass custom headers to the config and I'm not sure what the hell I'm doing wrong.

In my API I need to recieve always two headers for calculating the security hash, lets say secret1 and secret2, when I go to the config of CORS and I set in the config I do like this:

 paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['secret1, secret2']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
            max_age: 3600

Just Like I was doing in the VHost config

Header set Access-Control-Allow-Headers "secret1, secret2"

But when I set the config like I pasted, I have 200 status, but I don't receive the data, any idea?

The 'Access-Control-Allow-Origin' header contains the invalid value 'null'.

Im using jQuery to connect to the api.

Chrome is throwing this message:

XMLHttpRequest cannot load http://localhost/wharever/web/app_dev.php/api/wharever-admin/v1/user/csrf. The 'Access-Control-Allow-Origin' header contains the invalid value 'null'. Origin 'http://localhost:9000' is therefore not allowed access.

The config.yml:

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
    paths:
        '^/api/wharever-admin/':
            allow_credentials: true
            allow_origin: ['*']
            allow_headers: ['*']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600

The bundle works because when I delete the paths array I'm getting the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. 

Weird behavior.

he 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost', but only one is allowed.

XMLHttpRequest cannot load http://liveboard-dev.locastic.com/api/v1/login. The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost', but only one is allowed. Origin 'http://localhost' is therefore not allowed access.

nelmio_cors:
paths:
    '^/api/':
        allow_origin: ['*']
        allow_headers: ['*']
        allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
        max_age: 3600

Determine allowed methods from router

I think, would be nice have some magic in bundle to determine allowed methods based on router.

As I can debug all routers in console:

$ app/console router:debug
[router] Current routes
Name                       Method Pattern
app_vacancy_list           GET    /companies/{companyId}/vacancies
app_vacancy_post           POST   /companies/{companyId}/vacancies

I can determine, that for /vacancies URL will be allowed only two methods (GET, POST), right?

Is there a way to enable CORS for an image?

Hi,

Tanks for your bundle!
I was wondering if there is a way to enable CORS for an image (ie accessed directly from its own URL and not from a route).
I'm trying to modify this image from the front end using some javascript :

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var imgObj = new Image();
imgObj.crossOrigin = 'anonymous';
imgObj.src = src; // http://dev.myapp.com/files/image.jpg
canvas.width = imgObj.width;
canvas.height = imgObj.height;
ctx.drawImage(imgObj, 0, 0);
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height); // <== ERROR

getImageData function throws an error :

Image from origin 'http://dev.myapp.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

I've tried to add the following config to my config.yml file but it does not work :

'^/files/':
    allow_origin: ['*']
    allow_headers: ['*']
    allow_methods: ['GET']
    max_age: 3600
    allow_credentials: true

Do you know how to solve this problem? Accessing the image directly does not seems to run the symfony process and so it does not run the hooks of the bundle...
Any comments are appreciated,

thanks ๐Ÿ˜„

405 Error on OPTION request

Do I need to add something special to get the OPTIONS Request to work correctly currently I get an 405 Error Method not allowed.

My current test config is:

nelmio_cors:
    defaults:
        allow_credentials: true
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
    paths:
        # '^/api/':
        '^/':
            allow_origin: ['*']
            allow_headers: ['*']
            allow_methods: ['*'] # need to be changed to: ['POST', 'PUT', 'GET', 'DELETE]
            max_age: 3600

Here the response:

error405onrequest

Here my router:debug where you see the requested route is allowed for POST:

bildschirmfoto 2015-04-01 um 19 21 06

Symfony3

Will this support Symfony on version 3?

Duplicate control-header / control-origin

Hello,

I try to use this bundle for configure my api. But i have a problem since 2 weeks, and i didn't found any solution. Sorry for the inconvenience.
My last configuration is :

Project on server : Debian 8 / nginx / php-fpm

Server side : Symfony 3.0 with FosUserBundle/ FOSRestBundle/ NelmioApiDocBundle / NelmioCorsBundle/ LexikJWTAuthenticationBundle / JMSSerializer

My config.yml :

# FosUserBundle Configuration
fos_user:
    db_driver: orm
    firewall_name: main
    user_class: UserBundle\Entity\User
    group:
        group_class: UserBundle\Entity\Group
        form:
            type: UserBundle\Form\Type\GroupFormType
    profile:
        form:
            type: UserBundle\Form\Type\ProfileFormType

# FOSRestBundle Configuration
fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener: true
    view:
        view_response_listener: 'force'
        formats:
            xml: true
            json : true
        templating_formats:
            html: true
        force_redirects:
            html: true
        failed_validation: HTTP_BAD_REQUEST
        default_engine: twig
    routing_loader:
        default_format: json

# LexikJWTAuthenticationBundle Configuration
lexik_jwt_authentication:
    private_key_path: %jwt_private_key_path%
    public_key_path:  %jwt_public_key_path%
    pass_phrase:      %jwt_key_pass_phrase%
    token_ttl:        %jwt_token_ttl%

# JMSSerializer Configuration
jms_serializer:
    metadata:
        auto_detection: true

# NelmioCorsBundle Configuration
nelmio_cors:
    defaults:
        allow_credentials: true
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['Origin', 'Content-Type', 'X-Requested-With', 'Accept']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
            max_age: 3600

My security.yml :

api_doc:
    pattern: ^/api/doc
    anonymous: true

api_login:
    pattern:  ^/api/login
    provider: fos_userbundle
    stateless: true
    anonymous: true
    form_login:
        check_path:     /api/login_check
        require_previous_session: false
        username_parameter: username
        password_parameter: password
        success_handler:          lexik_jwt_authentication.handler.authentication_success
        failure_handler:          lexik_jwt_authentication.handler.authentication_failure

api:
    pattern:   ^/api
    stateless: true
    provider: fos_userbundle
    lexik_jwt:
        authorization_header:
            enabled: true
            prefix:  Bearer
        query_parameter:
            enabled: true
            name:    Bearer
        throw_exceptions:        true
        create_entry_point:      true

## Main firewall
main:
    pattern: ^/
    form_login:
        provider: fos_userbundle
        csrf_token_generator: security.csrf.token_manager
        login_path: fos_user_security_login
        check_path: fos_user_security_check
        remember_me: true
        default_target_path: lgb_onepage_home
    logout:
        path:   fos_user_security_logout
        target: lgb_onepage_home
    anonymous: true
    remember_me:
        secret:      %secret%
        lifetime: 604800 # 1 week in seconds
        path:     /
        domain:   ~ # Defaults to the current domain from $_SERVER
        #                secure:   true
        httponly: true

access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: ROLE_ADMIN }
    - { path: ^/resetting, role: ROLE_ADMIN }
    - { path: ^/intranet/, role: ROLE_USER }
    - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/doc, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api,       roles: [IS_AUTHENTICATED_FULLY, ROLE_ADMIN] }

And for my client, i use Ionic with angular JS on base project (with skeleton tabs for have a valid login form) :

My config :

.config(function ($stateProvider, $urlRouterProvider, localStorageServiceProvider, $httpProvider) {
    $stateProvider...;

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/app/playlists');

    localStorageServiceProvider
        .setPrefix('lgb-preorder');

    $httpProvider.defaults.headers.common = {};
    $httpProvider.defaults.headers.post = {};
    $httpProvider.defaults.headers.put = {};
    $httpProvider.defaults.headers.patch = {};
});

and my function (doesn't work):

$scope.doLogin = function () {

            var loginData = {
                username: this.login.username,
                password: this.login.password
            };

            $http({
                url: 'http://sub.domain.com/app_dev.php/api/login_check',
                method: 'POST',
                data: loginData,
                headers: {'Content-Type': 'application/json'}
            })
                .success(function (data) {
                    console.log("Success -- login ok with ", data);
                })
                .error(function (error) {
                    console.log("ERROR -- login fail with ", error);
                });
        };

Error send is :

XMLHttpRequest cannot load http://sub.domain.com/app_dev.php/api/login_check. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:8100', but only one is allowed. Origin 'http://localhost:8100' is therefore not allowed access.

it seems because my http request have 2 definitions of Access-Control-Allow-Headers and Access-Control-Allow-Origin :

Request URL:http://sub.domain.com/app_dev.php/api/login_check
Request Method:OPTIONS
Status Code:200 OK
Remote Address:x.x.x.x:80
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Headers:origin, content-type, x-requested-with, accept
Access-Control-Allow-Methods:POST, PUT, GET, DELETE, OPTIONS
Access-Control-Allow-Origin:http://localhost:8100
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600

but why ???____???
It seems i have 2 different handler, nelmio and one other, and each put an Access-Control-Allow-Headers / Access-Control-Allow-Origin. The others access-control are OK.

If anyone have an idea, its really appreciated. Thanx for your help.

No 'Access-Control-Allow-Origin' header is present on the requested resource

Okay I am desperate.

I am still getting this error when I am trying to post data by angular from different server:

XMLHttpRequest cannot load http://IP/app_dev.php/api/v1/pages.json. No 'Access-    Control-Allow-Origin' header is present on the requested resource. Origin      'http://127.0.0.1:9000' is therefore not allowed access. 

Remote Address:IP:80
Request URL:http://IP/app_dev.php/api/v1/pages.json
Request Method:OPTIONS
Status Code:200 OK
Request Headers
Accept:/
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,sk;q=0.6,cs;q=0.4
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:192.168.43.195
Origin:http://127.0.0.1:9000
Pragma:no-cache
Referer:http://127.0.0.1:9000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36

Response Headers
Access-Control-Allow-Headers:X-Requested-With, content-type
Access-Control-Allow-Methods:POST, GET, PUT, DELETE, OPTIONS
Connection:Keep-Alive
Content-Length:573
Content-Type:text/html; charset=iso-8859-1
Date:Sun, 29 Jun 2014 18:07:54 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.7 (Ubuntu)

I am trying to fix it all day long...

Currently I have:

# CORS OPTIONS (add this too)
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
    Header always set Access-Control-Allow-Headers "X-Requested-With, content-type"
</IfModule>

nelmio_cors:
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE','OPTIONS']
            max_age: 3600

Sending as:

            var data = new FormData;
            data.append('title', 'title');
            data.append('body', 'body');

            var request = $http({
                method: 'POST',
                url: TB+"/app_dev.php/api/v1/pages.json",
                headers: {
                    'Authorization': 'Bearer '+User.getAccessToken(),
                    'Content-Type': 'application/json'
                },
                data: data
            });

Any idea what's wrong with it please?

screenshot from 2014-06-29 20 20 01

Be able to force Access-Control-Allow-Origin header value

Current state

"Access-Control-Allow-Origin" header is set using the request's "Origin" header value (pre-flight request or not)

Issue

Let's say I have 2 differents hosts ("front1.example.com" and "front2.sample.com") which do AJAX calls to my API ("api.json.com").
But I also have a cache system (e.g. Varnish) which resend responses to already sent requests.
So when front1.example.com calls api.json.com, the "Access-Control-Allow-Origin" header of the response is front1.example.com.
But when front2.sample.com calls api.json.com with the same URL, my cache system reuse the previous response, so the "Access-Control-Allow-Origin" header of the response is still front1.example.com... and the browser say "You're not allowed... Cross origin blabla...".

Possible fix

Add a configuration option to let the user set the value of the header "Access-Control-Allow-Origin" to be * for instance... or anything else.

XMLHttpRequest cannot load http://127.0.0.1:8000/api/login_check. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

XMLHttpRequest cannot load http://127.0.0.1:8000/api/login_check. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Ajax request is terminated when origin is not allowed

First, nice work ;-)

I'm working on API which is requested from normal www website and browser extensions for Chrome and FF. When I call API from website I can add my website to allowed origins and it works perfectly ok.

My real problem is that when I call my API from browser extension origin can by any address of any website on internet. In this case CorsListener is responding with 403 Forbidden in line https://github.com/nelmio/NelmioCorsBundle/blob/master/EventListener/CorsListener.php#L78. I'm currious why? I have also checked CORS specyfication on http://www.w3.org/TR/cors/#resource-requests and didn't find any information that it should terminate the request and send 403 Forbidden when origin is not allowed.

I can prepare patch and remove this line (just return without setting 403 Forbidden response) but do you agree on this sollution?

Getting 400 Bad Request on OPTIONS request

Hi !

I'm trying to use NelmioCors along with the fos rest bundle.

For now, I'm just doing basic tests like posting data from a different domain than the api one. But doing so, I'm getting HTTP 400 errors on the OPTIONS requests.

Here is my NelmioCors config:

nelmio_cors:
    paths:
        '^/':
            allow_credentials: false
            allow_origin: ['*']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE','OPTIONS']
            max_age: 1728000

And here is what I have in Chrome debug console:

Remote Address:127.0.0.1:80
Request URL:http://127.0.0.1/tests/app_dev.php/api/v1/customers
Request Method:OPTIONS
Status Code:400 Bad Request

Request Headers
 Accept:*/*
 Accept-Encoding:gzip, deflate, sdch
 Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,pl;q=0.2
 Access-Control-Request-Headers:content-type
 Access-Control-Request-Method:POST
 Connection:keep-alive
 Host:127.0.0.1
 Origin:http://0.0.0.0:9000
 Referer:http://0.0.0.0:9000/
 User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko)  Chrome/39.0.2171.95 Safari/537.36

Response Headers
 Access-Control-Allow-Methods:POST, PUT, GET, DELETE, OPTIONS
 Access-Control-Allow-Origin:http://0.0.0.0:9000
 Access-Control-Max-Age:1728000
 Cache-Control:no-cache
 Connection:close
 Content-Type:text/html; charset=UTF-8
 Date:Thu, 15 Jan 2015 18:33:36 GMT
 Server:Apache/2.4.9 (Unix) PHP/5.5.14
 Transfer-Encoding:chunked
 X-Debug-Token:c9e4ff
 X-Powered-By:PHP/5.5.14

What am I doing wrong ? Should NelmioCors manage the OPTIONS request or should I do something specific for this ?

Caching OPTIONS requests

Hello,

Thanks for your bundle, it works like a charm.
I'm able to send cross origin requests, but it's sending an OPTIONS request before every other call. I'd like to cache those, I guess that's what the max_age option is meant for.

I think this was supposed work, here is the config I'm using:

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['Api-Key', 'Origin', 'Content-Type']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600

Am I missing something?
Thanks!

"Method not allowed" with a PreAuth

Hi,

I've created an ApiKeyAuthenticator in my api bundle following this cookbook http://symfony.com/doc/2.7/cookbook/security/api_key_authentication.html#handling-authentication-failure

When I call any method, I get a "405 Method Not Allowed" error.
I think that security configuration (http://symfony.com/doc/2.7/cookbook/security/api_key_authentication.html#configuration) give a higher priority to PreAuth rather than CorsListener.

Is there a way to use CorsListener with PreAuth ?

Preflight error 401 with Symfony 3.1.3

Hi,

CORS preflight calls are being rejected with a 401 error code on my API since I tried upgrading to Symfony 3.1.3.
I am using NelmioCorsBundle 1.4.1.
My API is protected by a firewall which requires authentication, so I guess the CORS listener is being called too late...

Symfony 3.1.2 works just fine, so a commit in-between must have broken the CORS preflight calls. I'd say either [Security] fixed DebugAccessDecisionManager::setVoters() or [HttpFoundation] Add OPTIONS and TRACE to the list of safe methods

Here is a log of my issue if that can help you:
security.INFO: An AuthenticationException was thrown; redirecting to authentication entry point. {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AuthenticationCredentialsNotFoundException(code: 0): A Token was not found in the TokenStorage. at /website/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/AccessListener.php:53)"}

Thanks, regards,

Nicolas

A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true

I using FOSRestBundle with Nelmio Cors Bundle and have some endpoints, /api/name_end_points and I need for some server have authority to call this endpoints.
Now I have error in console

XMLHttpRequest cannot load http://mydomain.com.com/api/endpoint?value=test&value1=test. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3000' is therefore not allowed access.

This my config:

fos_rest:
param_fetcher_listener: true
body_listener: true
format_listener: true
view:
    view_response_listener: 'force'
    formats:
        xml: true
        json : true
    templating_formats:
        html: true
    force_redirects:
        html: true
    failed_validation: HTTP_BAD_REQUEST
    default_engine: twig
routing_loader:
    default_format: json

nelmio_cors:
defaults:
    allow_credentials: false
    allow_origin: []
    allow_headers: []
    allow_methods: []
    expose_headers: []
    max_age: 0
    hosts: []
    origin_regex: false
paths:
    '^/':
        allow_origin: ['*']
        allow_headers: ['*']
        allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
        max_age: 3600

How to correct config NelmioCorsBundle if I want access true for some server for my endpoints ?
Like this

        allow_origin: ['*aog.jobs*', '*localhost*']

and deleted default ?

Bad response headers for preflight OPTIONS requests

Hi,

I'm bulding an app on top of ezplatform & symfony and I'm currently trying to use the JS REST API provided by ezplatform.

Here are my nelmio_cors configs :

nelmio_cors:
    paths:
        '^/api/ezp/v2/':
            max_age: 3600
            allow_credentials: true
            allow_origin: ['*']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
            expose_headers: []

Trying to request my app from an other domain (cors requests) I'm stuck with this error which occurs during preflight requests.
Response for preflight has invalid HTTP status code 405 (from Google Chrome)

Looking at the response headers, I noted that the response headers were not the ones I was hoping for. At least, this header is missing :
Access-Control-Allow-Methods: POST, PUT, GET, DELETE, OPTIONS

Looking inside the nelmio_cors bundle code, I figured out that this code form CorsListener is never reached :

if ($options['allow_methods']) {
      $response->headers->set('Access-Control-Allow-Methods', implode(', ', $options['allow_methods']));
}

It seems that $options is empty or at least doesn't contains the good values.

I don't know if there is a bug here or if I' missing something. I also posted this question on stackoverflow (for more detail)

Thanks in advance for help

Better documentation

Can you please add, that 'paths:' is required inside the config?

I removed it because in my use case I am working with the subdomain api.domain.com and that caused to a not working extension.

So that directs me to a questions, how do I config the extension to work for a specific subdomain (api) only? Path seems to not work here?
Thank you.

Allow URL parameters

Hi,

Thanks for your bundle ๐Ÿ‘
I'm having troubles when accessing to an address with URL parameters :

GET http://my.symfony.root.url/efconnect?cmd=open&target=&init=1&tree=1&_=1423215615264

Status 200 OK, Cross-Origin Request blocked.

I've though allowed the ^/efconnect path in my nemlio cors config.
You can have more details about my problems here : helios-ag/FMElfinderBundle#106

It seems like URL parameters are not well handled ๐Ÿ˜ฎ .
I'm not sure this problem may concern your bundle or not. If not, sorry for disturbance ๐Ÿ˜› .
Thanks for help ๐Ÿ˜‰

XMLHttpRequest fail when server returns 302

I get requests fail when I try to authorize (authorization redirects to /success or /fail)

Chrome console gives me:
XMLHttpRequest cannot load /web/app_dev.php/user/authorization The request was redirected to /web/app_dev.php/login/fail, which is disallowed for cross-origin requests that require preflight.

Here is my config:

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
    paths:
        '^/':
            allow_origin: ['http://server.dev', 'http://localhost', 'http://127.0.0.1']
            allow_headers: ['Origin', 'Content-Type', 'Accept']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            expose_headers: ['*']
            max_age: 3600

Origin not validated correctly for GET requests

Hello,

I have the following configuration, with a standard Symfony 2.5 installation:

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: ['http://example.com']
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
    paths:
        '^/':
            allow_origin: ['http://example.com']
            allow_headers: []
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
            max_age: 3600

I am making a GET request using curl, with a different domain (http://boo.com) as the origin. The request is allowed, by the presence of the following header in the response:

Access-Control-Allow-Origin: http://boo.com

Here's the curl command I used:
curl -H "Origin: http://boo.com" --verbose http://symfony25.local/app_dev.php

From looking through the code, I see that the origin check is only performed for pre-flight requests. But pre-flight requests are only sent by browsers with PUT and DELETE requests, and not with GET and POST requests (see: http://stackoverflow.com/questions/15381105/cors-what-is-the-motivation-behind-introducing-preflight-requests).

In CorsListener.php, within the onKernelResponse() function, I see the following line:

$response->headers->set('Access-Control-Allow-Origin', $request->headers->get('Origin'));

In this case, it's simply echo'ing back the Origin specified by the client, instead of validating it against the list of valid origins in the configuration file.

The only origin check happens within the checkOrigin() function, but this function is only called when the OPTIONS header is sent (for pre-flight requests).

Please let me know if I'm missing something in the configuration, or doing something wrong. But from the looks of it, this appears to be a serious bug. As a side note, this same behavior probably applies to POST requests as well, although I haven't tested that yet.

Finally, I tried removing "GET" from the list of allow_methods in the configuration file, but this did not prevent the same "Access-Control-Allow-Origin: http://boo.com" header from being sent back.

Use annotation on CORS-enabled routes

I think it would be nice to be able to add an annotation to a route for which you want to enable CORS.

/**
* @Route("/your/cors/enable/route")
* @Method("POST")
* @Cors()
*/
public function login()
{
    return new Response("...");
}

You could optionally provide a key of a configuration, if you don't want to use the default values. e.g. @Cors("api")

In this way, you are far more flexibel in configuration (you loose al the pattern matching stuff) and it makes cors enabling more verbose.

Any thoughts?

use along with HTTP cache

Hi !

I'm using the NelmioCorsBundle along with FosRestBundle and HTTP caching.

In one of my REST enpoint, I'm doing this:

            $response = $this->handleView($this->view($ret, 200));

            $response->setPublic();
            $response->setMaxAge(21600);
            $response->setSharedMaxAge(21600);
            $response->headers->addCacheControlDirective('must-revalidate', true);

            return $response;

In that case, the CORS header aren't set on the response. What am I missing ?

Note that it is working fine if I'm not http caching the response...

Also, here is my NelmioCors config:

nelmio_cors:
    paths:
        '^/':
            allow_credentials: false
            allow_origin: ['*']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
            allow_headers: ['Content-Type', 'Authorization']
            max_age: 1728000

405 When Access-Control-Request-Method Isn't Set

Not sure if bug or feature:

When using this in combination with the NelmioApiDocBundle I noticed that the sandbox didn't work when making request with a json body. I figured out that the sandbox was performing a OPTIONS request without an "Access-Control-Request-Method" header, and tracked the issue down to line 135 in @NelmioCorsBundle/EventListner/CorsListener.php:

if (!in_array($request->headers->get('Access-Control-Request-Method'), $options['allow_methods'], true)) {

It works with this tweak:

if (!is_null($request->headers->get('Access-Control-Request-Method')) && !in_array($request->headers->get('Access-Control-Request-Method'), $options['allow_methods'], true)) {

โ€œ405 method not allowedโ€. It's allright sending the request from a HTTP simulation web

Im getting a 405 when sending a POST request to "http://www.sermobi.com/customers" from a mobille app using an ajax function.

But I don't get that error using a tool like http://www.hurl.it/#top.

I have already enable CORS on my server and checked that it works ok for GET requests. I have also enabled it for POST requests. At my app/config.yml:

nelmio_cors:
    paths:
        '^/':
            allow_origin: ['*']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600

I have already checked the access log and this is what I get after the POST request:

www.sermobi.com:80 81.35.17.182 - - [24/Jul/2014:18:44:38 +0200] "POST /new HTTP/1.1" 405 1009 "-" "Mozilla/5.0 (Linux; Android 4.4.3; One S Build/KTU84M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36"

Any help?

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.