跳到内容

@Security & @IsGranted

编辑此页
在当前的 Symfony 应用中,不再建议使用此捆绑包。此捆绑包提供的所有注解现在都内置在 Symfony 中,作为 PHP 属性。查看 Symfony 属性的完整列表

用法

@Security@IsGranted 注解限制对控制器的访问

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

class PostController extends Controller
{
    /**
     * @IsGranted("ROLE_ADMIN")
     *
     * or use @Security for more flexibility:
     *
     * @Security("is_granted('ROLE_ADMIN') and is_granted('ROLE_FRIENDLY_USER')")
     */
    public function index()
    {
        // ...
    }
}

@IsGranted

@IsGranted() 注解是限制访问的最简单方法。使用它按角色限制,或者使用自定义投票器根据传递给控制器的变量来限制访问

1
2
3
4
5
6
7
8
9
/**
 * @Route("/posts/{id}")
 *
 * @IsGranted("ROLE_ADMIN")
 * @IsGranted("POST_SHOW", subject="post")
 */
public function show(Post $post)
{
}

每个 IsGranted() 都必须授予用户访问控制器的权限。

提示

@IsGranted("POST_SHOW", subject="post") 是使用自定义安全投票器的示例。有关更多详细信息,请参阅 安全投票器页面

您还可以控制消息和状态码

1
2
3
4
5
6
7
8
9
10
11
12
/**
 * Will throw a normal AccessDeniedException:
 *
 * @IsGranted("ROLE_ADMIN", message="No access! Get out!")
 *
 * Will throw an HttpException with a 404 status code:
 *
 * @IsGranted("ROLE_ADMIN", statusCode=404, message="Post not found")
 */
public function show(Post $post)
{
}

@Security

@Security 注解比 @IsGranted 更灵活:它允许您传递一个可以包含自定义逻辑的表达式

1
2
3
4
5
6
7
/**
 * @Security("is_granted('ROLE_ADMIN') and is_granted('POST_SHOW', post)")
 */
public function show(Post $post)
{
    // ...
}

表达式可以使用您可以在安全捆绑包配置的 access_control 部分中使用的所有函数,以及 is_granted() 函数。

表达式可以访问以下变量

  • token: 当前安全令牌;
  • user: 当前用户对象;
  • request: 请求实例;
  • roles: 用户角色;
  • 以及所有请求属性。

您可以使用 statusCode 选项抛出 Symfony\Component\HttpKernel\Exception\HttpException 异常,而不是 Symfony\Component\Security\Core\Exception\AccessDeniedException

1
2
3
4
5
6
/**
 * @Security("is_granted('POST_SHOW', post)", statusCode=404)
 */
public function show(Post $post)
{
}

message 选项允许您自定义异常消息

1
2
3
4
5
6
/**
 * @Security("is_granted('POST_SHOW', post)", statusCode=404, message="Resource not found.")
 */
public function show(Post $post)
{
}

提示

您还可以在控制器类上添加 @IsGranted@Security 注解,以阻止访问该类中的所有操作。

此作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本