使用注释的安全方法

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));
    }

这将保护整个功能,但我想访问它,而不是 POST 在未登录的情况下访问它。另一种方法是检查 $form 中是否有登录用户->isValid() 括号。但是我还在想能不能用注解来完成

你可以这样做。

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

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