【问题标题】:Secure method using annotations使用注释的安全方法
【发布时间】:2016-04-26 09:49:14
【问题描述】:

我有一个带有表单的页面,想知道是否可以使用 GET 访问它,但只允许登录用户向它发布。

我知道这可以在 security.yml 中完成,但我不确定如何使用注释来完成。

 /**
     * @param Request $request
     * @return Response
     * @Security("has_role('ROLE_USER')")
     * @Method(methods={"POST"})
     */
    public function calculatorAction(Request $request)
    {

        $form=$this->createForm(new CallRequestType(),$callReq=new CallRequest());


        $form->handleRequest($request);

        if($form->isValid()){
            //blabla
        }


        return $this->render('MyBundle:Pages:calculator.html.twig', array('form' => $form));
    }

这将保护整个功能,但我想访问它,而不是在没有登录的情况下发布到它。另一种方法是检查 $form->isValid() 括号中是否有登录用户.但是我仍然想知道是否可以使用注释来完成。

【问题讨论】:

  • 一点题外话:@Method 注释仅在使用 @Route 注释的操作时才考虑。
  • 很高兴知道,我不知道。
  • 我建议你分成两种不同的方法
  • 我也这么想,但不想。以为有替代方案。那我想我会同意的。

标签: php symfony symfony-security


【解决方案1】:

你可以做这样的事情。

您可以匿名允许这两种方法类型,并仅在控制器内部检查用户是否已通过身份验证并正在发布。

(你没有说明你使用的是哪个版本的 symfony,所以你可能需要用 authorization_checker (2.8) 替换旧的 security.context 服务)

/**
 * @param Request $request
 * @return Response
 *
 * @Route("/someroute", name="something")
 * @Method(methods={"POST", "GET"})
 */
public function calculatorAction(Request $request)
{

    if ( !$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY') && $request->getMethod() == 'POST') {
        throw new AccessDeniedHttpException();
    }


    $form=$this->createForm(new CallRequestType(),$callReq=new CallRequest());


    $form->handleRequest($request);

    // you also need to check submitted or youll fire the validation on every run through.
    if($form->isSubmitted() && $form->isValid()){
        //blabla
    }


    return $this->render('MyBundle:Pages:calculator.html.twig', array('form' => $form));
}

【讨论】:

  • authorization_checker 在 2.8 之前也可用,但是是的,我使用的是 2.8。这就是我最终要做的。我正在寻找一种在控制器外部进行检查的方法。
猜你喜欢
  • 2013-10-21
  • 2012-01-04
  • 1970-01-01
  • 2010-10-05
  • 2011-07-10
  • 2012-01-01
  • 1970-01-01
  • 2015-09-20
  • 2016-04-05
相关资源
最近更新 更多