drwu24647 2013-03-20 09:18
浏览 17
已采纳

Symfony2:检查控制器中的用户对象,最佳实践

Is it a good idea to check in the controller that the object called by getUser() of security.context service is actually an object of my custom user class?

public function editAction()
{
    $user = $this->container->get('security.context')->getToken()->getUser();
    if (!is_object($user) || !$user instanceof \Acme\UserBundle\User) {
        throw new AccessDeniedException('This user doesn't have access');
    }

    // work with $user
    // ....

The only thing that is guaranteed is that getUser() returns an object that implemented Symfony\Component\Security\Core\User\UserInterface, nothing else, right?

This means that the controller may potentially receive any type of object (a token anonymous maybe) so if I pass (without control it) the object directly to the view that subsequently call {{ user.biography }}, which is implemented only in Acme\UserBundle\User class .., I'd be making an error?

  • 写回答

2条回答 默认 最新

  • duanbei2914 2013-03-20 09:59
    关注

    It's a good idea if your configuration allows that possibility. This could happen if you allow anonymous users or have more than one type implemented.

    Of you implement multiple user types it might be a good idea to make them share a common interface. You can also override the "getRole" method on each class so each type returns a extra role defining it's type and then use access control to filter undesired types out.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?