使用注释的安全方法


Secure method using annotations

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

我知道这可以在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() 括号中是否有登录用户。但我仍然想知道它是否可以用注释来完成。

你可以做这样的事情。

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

(你没有说明你使用的是哪个版本的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));
}