我创建了一个带评论系统的博客,我希望作者或管理员删除他的评论。
所以我搜索了互联网,但我发现只有参考Symfony 2/3的帖子,我很难理解。
所以我创建了自己的功能
/**
* @Route("/blog/commentDelete/{id}-{articleId}-{articleSlug}", name="comment_delete")
*/
public function commentDelete($id, $articleId, $articleSlug, CommentRepository $commentRepository, AuthorizationCheckerInterface $authChecker){
$em = $this->getDoctrine()->getManager();
$comment = $commentRepository->find($id);
$user = $this->getUser();
if ($user->getId() != $comment->getAuthor()->getId() && $authChecker->isGranted('ROLE_MODERATOR') == false ){
throw exception_for("Cette page n'existe pas");
}
$em->remove($comment);
$em->flush();
$this->addFlash('comment_success', 'Commentaire supprimé avec succès');
return $this->redirectToRoute('blog_show', array('id' => $articleId, 'slug' => $articleSlug));
}
在树枝上,我有这个链接:
<a href="{{ path('comment_delete', {'id': comment.id, 'articleId': article.id, 'articleSlug': article.slug}) }}">Supprimer</a>
我需要操作的注释ID,以及文章id和文章slug在删除注释后重定向用户。
我检查删除评论的人是作者还是主持人。
但是,我听说绝对不安全,因为我必须使用表单,但我真的不知道如何在这种情况下使用表单...或者可能用JS来隐藏最终用户的链接?
所以我想知道我的功能是否足够安全,或者是否存在更好的解决方案以及如何实现它?
保护删除操作的一种方法是执行以下操作:
<?php
namespace App\Security\Voter;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use App\Entity\Comment;
class CommentVoter extends Voter
{
const CAN_DELETE = 'CAN_DELETE';
protected function supports($attribute, $subject)
{
return in_array($attribute, [self::CAN_DELETE]) && $subject instanceof Comment;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof User) {
return false;
}
/** @var Comment $comment */
$comment = $subject;
switch ($attribute) {
case self::CAN_DELETE:
return $this->canDelete($comment, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canDelete(Comment $comment, User $user)
{
if($user->getId() !== $comment->getAuthor()->getId() && $user->hasRole('ROLE_MODERATOR') === false) {
return false;
}
return true;
}
}
在您的用户实体中,hasRole方法可以是:
/**
* @param string $role
*/
public function hasRole(string $role)
{
return in_array(strtoupper($role), $this->getRoles(), true);
}
{% if is_granted('CAN_DELETE', comment) %}
<form action="{{ path('comment_delete', {'id': comment.id, 'articleId': article.id, 'articleSlug': article.slug}) }}" method="post">
<input type="hidden" name="_csrf_token" value="{{csrf_token('delete_comment')}}" />
<button>supprimer</button>
</form>
{% endif %}
/**
* @Route("/blog/commentDelete/{id}-{articleId}-{articleSlug}", methods={"POST"}, name="comment_delete")
*/
public function commentDelete($id, $articleId, $articleSlug, CommentRepository $commentRepository, EntityManagerInterface $em){
$comment = $commentRepository->find($id);
$csrfToken = $request->request->get('_csrf_token');
if(!$this->isCsrfTokenValid('delete_comment', $csrfToken) || !$this->isGranted('CAN_DELETE', $comment){
throw exception_for("Cette page n'existe pas");
}
$em->remove($comment);
$em->flush();
$this->addFlash('comment_success', 'Commentaire supprimé avec succès');
return $this->redirectToRoute('blog_show', array('id' => $articleId, 'slug' => $articleSlug));
}
这里你的删除方法受csrf令牌和选民的保护。我认为这是一种解决方案。
为了解决这类问题,我建议使用Symfony Voters https://symfony.com/doc/current/security/voters.html
你正朝着正确的方向前进。始终在后端进行验证和权限检查。
隐藏链接或使用表单并将其设置为禁用将不会阻止使用dev-tools的人员将请求发送到您的控制器。我宁愿将前端检查视为用户的便利 - 在发出请求之前直接向他们展示某些数据无效/他们不允许做某事。
我正在使用SensioFrameworkExtraBundle进行ROLE检查(我仍然不喜欢这种检查的注释......嗯) - 如果用户没有得到控制器操作的拟合角色,则抛出permissionDeniedException。接下来可能需要像$user->getId() != $comment->getAuthor()->getId()
那样进行进一步的检查