我通常会创建一个服务来检查用户的角色,通过投票者呼叫(如果需要,我可以提供一个示例)来检查特定权限,例如“此用户可以更新此特定帖子吗?SecurityAccessManager
配置
company.navigation.security_access:
class: Company\NavigationBundle\Services\SecurityAccessManager
arguments:
- @security.authorization_checker
- @security.token_storage
服务代码
namespace Company\NavigationBundle\Services;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class SecurityAccessManager
{
private $authorizationChecker;
private $tokenStorage;
private $debug;
public function __construct(
AuthorizationCheckerInterface $authorizationChecker,
TokenStorage $tokenStorage)
{
$this->authorizationChecker = $authorizationChecker;
$this->tokenStorage = $tokenStorage;
$this->debug = true;
}
// *************************************************************************
// User
// *************************************************************************
public function getUser()
{
return $this->tokenStorage->getToken()->getUser();
}
public function getUserId()
{
return $this->tokenStorage->getToken()->getUser()->getId();
}
public function isAuthenticatedUser()
{
return $this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED');
}
// *************************************************************************
// Roles checker
// *************************************************************************
public function isAdmin()
{
if($this->authorizationChecker->isGranted('ROLE_ADMIN') !== true) {
return false;
} else {
return true;
}
}
public function checkRightAdmin()
{
if($this->authorizationChecker->isGranted('ROLE_ADMIN') !== true) {
throw new AccessDeniedException('Unauthorised access! '.($this->debug ? __FUNCTION__ : null));
}
return true;
}
public function checkUserHasRightToEditPost($postId)
{
// Check if user has right to modify the post
if ($this->authorizationChecker->isGranted('is_user_has_right_to_edit_post', $postId) === false) {
throw new AccessDeniedException('Unauthorised access! '.($this->debug ? __FUNCTION__ : null));
}
return true;
}
}
然后,在控制器操作中,您可以检查用户的权限
namespace Company\YourBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class YourBunbleController extends Controller
{
/**
* Get the service
* @return \Company\NavigationBundle\Services\SecurityAccessManager
*/
private function getService()
{
return $this->get('company.navigation.security_access');
}
public function updatePostAction(Request $request, $postId)
{
// Throw 403 if user has no admin rights
$this->getService()->checkRightAdmin();
// Throw 403 if user has no rights to update the post
$this->getService()->checkUserHasRightToEditPost();
//OK, you can update database
...
}
}