简体   繁体   中英

Deny access in Symfony method unless you are in localhost

I want to know how to deny the access to a controller method that it isn't being called from localhost . For example, I would like to allow the access to this URL www.myweb.com/usermanagement only if you are on localhost.

I didn't find anything on doc https://symfony.com/doc/3.2/security.html

Look in the access_control documentation . You can use the allow_if key and do something like this:

access_control:
    - path: ^/usermanagement
      allow_if: "request.getHost() == 'localhost'"

First, the solution of fxbt is great.

But you can also do it by using the firewall configuration in security.yaml file: https://symfony.com/doc/3.2/security/firewall_restriction.html

# app/config/security.yml

# ...
security:
    firewalls:
        # This is a custom firewall area and may conflict with your existing firewall
        other_secured_area:
            host: ^localhost$
            pattern: ^/usermanagement

Another solution is to do it directly in the controller:

public function userManagement(Request $request)
{
    if ($request->getHost() !== 'localhost') {
        throw new $this->createAccessDeniedException();
    }
}

In any case by careful because host security may not be the best security (it's possible to manipulate the host from the client in most cases).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM