yozawiratama
yozawiratama

Reputation: 4318

Symfony 3 Nelmio cors set allow origin properly

I want to give limit access only allow some address to access my restful API, I using symfony and nelmio cors bundle.

this is my config from documetation :

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
        forced_allow_origin_value: ~
    paths:
        '^/api':
            allow_origin: ['192.0.74.122']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'DELETE']
            max_age: 3600
        '^/':
            origin_regex: true
            allow_origin: ['^http://localhost:[0-9]+']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
            hosts: ['^api\.']

I want to set 192.0.74.122 only allowed to access the ^/api and ^/api/*, but when I test in browser, postman and jquery ajax call, it can be from localhost or 127.0.0.1.

please help me how to block from other address beside the allowed addresses?

Upvotes: 0

Views: 3539

Answers (1)

gblock
gblock

Reputation: 604

Nelmio cors bundle is about setting CORS headers not about blocking or restricting access to specific routes.

Use access_control entries in your security.yml for that. Example (not tested):

# config/security.yml
security:
    # ...
    access_control:
        - { path: ^/api, role: IS_AUTHENTICATED_ANONYMOUSLY, ip: 192.0.74.122 }
        - { path: ^/api, role: ROLE_NO_ACCESS }

You can set multiple IPs or even ranges. See the official cookbook page a for detailed explanation.

Upvotes: 2

Related Questions