执行控制器前的自定义授权检查

时间:2015-11-10 07:40:32

标签: symfony authorization symfony-routing

我在路由设置中添加了一个新选项public static String doHttpUrlConnectionAction(String desiredUrl, String cookieValue) throws Exception { URL url = null; BufferedReader reader = null; StringBuilder stringBuilder; try { url = new URL(desiredUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // just want to do an HTTP GET here connection.setRequestMethod("POST"); // connection.setDoOutput(true); // give it 15 seconds to respond String cookie = CookieManager.getInstance().getCookie(new URL("https://exaperth.exacrm.com").getHost()); System.out.println("Cookie from cookie store: " + cookie); connection.setRequestProperty("Cookie", cookie); connection.setReadTimeout(15 * 1000); connection.connect(); // read the output from the server reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); stringBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line + "\n"); } return stringBuilder.toString(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { // close the reader; this can throw an exception too, so // wrap it in another try/catch block. if (reader != null) { try { reader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } } ,用于在菜单渲染期间检查菜单项的权限。
如果我可以在执行相应的控制器之前使用选项进行授权检查,那就太棒了。

示例:

roles

在执行控制器本身之前,我需要检查用户是否可以根据自己的角色访问控制器 怎么可能?有什么想法吗?

更新
为什么我需要some_route: path: /path/ defaults: { _controller: MyBundle:Controller:action } option: roles: [ROLE_MANAGER, ROLE_ADMIN] 选项?
项目中有4个不同的角色和许多路线。某些路由受到保护,仅对具有特定角色的用户可见 目前,所有授权检查都是通过roles方法在控制器内执行的 我还使用KnpMenuBundle来构建菜单。在菜单渲染期间,我需要检查当前登录用户的每个项目的可访问性。如果用户无权访问某个项目,则会将其排除在外,用户也无法看到该项目 为了检查用户是否有权访问某个项目,我添加了我提到的选项,其中我定义了可以访问路径的角色。此denyAccessUnlessGranted()选项定义的绝对角色与roles中的检查完全相同。我认为,由于我已经拥有这些角色设置,为什么不将它用于控制器授权检查并从中删除冗余代码。

2 个答案:

答案 0 :(得分:3)

基本上有两种方式

  1. <强> Security.yml

    - { path: ^/path/$, roles: [ROLE_MANAGER, ROLE_ADMIN] }
    
  2. 直接注入控制器

    /**
     * @Security("has_role('ROLE_ADMIN') or has_role('ROLE_MANAGER')")
     */
    public function nameOfYourAction()
    
  3. 这样,在控制器执行动作之前完成的第一个动作是安全检查:如果失败,控制器将不会被执行。

答案 1 :(得分:1)

我知道这不是一个答案,但是你要求它。

添加kernel.controller侦听器并检查其中的权限。