leaseweb/secure-controller-bundle

通过指定所需角色,为控制器中的安全动作提供 '@Secure' 注解

v1.1.0 2016-03-08 10:35 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:55:34 UTC


README

通过指定所需角色,为控制器中的安全动作提供 '@Secure' 注解。

注意:您可能想要使用 SensioFrameworkExtraBundle(Symfony 2.4+ 特性)提供的 @Security 注解 而不是此包。

注意:创建此包是因为 JMSSecurityExtraBundle 已不再在 Symfony 2.3 中提供(由于许可证不兼容),而我们只需要这个功能。

Build Status

要求

  • PHP 5.3
  • Symfony 2.8

安装

安装分为以下步骤

  1. 使用 composer 下载 LswSecureControllerBundle
  2. 启用 Bundle

步骤 1:使用 composer 下载 LswSecureControllerBundle

在您的 composer.json 中添加 LswSecureControllerBundle

{
    "require": {
        "leaseweb/secure-controller-bundle": "*",
        ...
    }
}

现在运行以下命令让 composer 下载此包

$ php composer.phar update leaseweb/secure-controller-bundle

Composer 将安装此包到您项目的 vendor/leaseweb 目录。

步骤 2:启用 Bundle

在 kernel 中启用 Bundle

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new Lsw\SecureControllerBundle\LswSecureControllerBundle(),
    );
}

用法

以下示例展示了如何在 AcmeDemoBundle 中使用 '@Secure' 注解来保护“hello world”页面,要求“ROLE_TEST”角色才能执行。

src/Acme/DemoBundle/Controller/SecuredController.php 文件中,您应该在命名空间定义之后添加以下行:

use Lsw\SecureControllerBundle\Annotation\Secure;

要为“SecuredController”中的“helloAction”要求“ROLE_TEST”角色,您应该像这样在“helloAction”的 DocBlock 中添加 @Secure(roles="ROLE_TEST")

    /**
     * @Secure(roles="ROLE_TEST")
     * @Route("/hello", defaults={"name"="World"}),
     * @Route("/hello/{name}", name="_demo_secured_hello")
     * @Template()
     */
    public function helloAction($name)
    {
        return array('name' => $name);
    }

或像这样添加到控制器本身的 DocBlock 中

    /**
     * @Secure(roles="ROLE_TEST")
     */
    class AdminController extends Controller
    {
      ...
    }

如果用户没有此角色,当访问动作时应该出现以下错误

Current user is not granted required role "ROLE_TEST".
403 Forbidden - AccessDeniedHttpException
1 linked Exception:

如果将“@Secure”注解放在不背后有防火墙的动作上,您将得到以下错误

@Secure(...) annotation found without firewall on "helloAction" in 
".../src/Acme/DemoBundle/Controller/DemoController.php"
500 Internal Server Error - AuthenticationCredentialsNotFoundException

请注意,您可以在 app/config/security.yml 中配置防火墙。

致谢

如果没有 Matthias Noback 的出色帖子,这不可能实现

贡献者

许可证

此包采用 MIT 许可证。