심포니 CSRF and Ajax
심포니 2 프로젝트에 아약스 기능을 구현하려고 합니다.jquery의 $.post를 사용하여 컨트롤러로 데이터를 다시 보내고 싶습니다.그러나 데이터를 게시만 하면 symphony의 crf 보호는 양식에만 적용되는 것처럼 보이기 때문에 CSRF 보호가 적용되지 않습니다.
이를 구현하는 아주 간단한 방법은 무엇입니까?
양식을 사용할 때 CSRF 토큰이 통과하는지 여부를 확인하기 위해 $form-> is Valid()만 하면 됩니다.저는 현재 제가 포스팅하고 싶은 모든 것을 양식에 담아 포스팅하고 있습니다.기본적으로 저는 CSRF 보호를 구현하기 위해서만 그 양식을 사용하고 있다는 것을 의미합니다. 이것은 해킹된 것처럼 보입니다.
Symfony2 CSRF 토큰은 기본적으로 세션을 기반으로 합니다.생성하려면 다음과 같은 서비스와 호출 생성 방법을 얻기만 하면 됩니다.
//Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider by default
$csrf = $this->get('form.csrf_provider');
//Intention should be empty string, if you did not define it in parameters
$token = $csrf->generateCsrfToken($intention);
return new Response($token);
이 질문은 당신에게 유용할 것입니다.
간헐적으로 이런 문제가 있었습니다.알고 보니 그건 내 아약스 때문이 아니라 실렉스가 당신에게 감가상각금을 주었기 때문입니다.DefaultCsrfProvider
세션 ID 자체를 토큰의 일부로 사용하고 보안을 위해 임의로 ID를 변경합니다.대신에, 새로운 것을 사용하라고 명시적으로 말하는 것.CsrfTokenManager
는 토큰을 생성하여 세션에 저장하므로 토큰의 유효성에 영향을 주지 않고 세션 ID를 변경할 수 있습니다.
/** Use a CSRF provider that does not depend on the session ID being constant. We change the session ID randomly */
$app['form.csrf_provider'] = $app->share(function ($app) {
$storage = new Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage($app['session']);
return new Symfony\Component\Security\Csrf\CsrfTokenManager(null, $storage);
});
이 토막글을 사용해 보세요.Symfony 양식은 포스트 요청과 함께 전송해야 하는 특수 _csrf_token을 생성해야 합니다.이 값이 없으면 보안 경고가 발생합니다.
물론 #targetForm은 formid로, /endpoint는 targetajaxurl로 대체해야 합니다.
$('#targetForm').bind('submit', function(e) {
e.preventDefault();
var data = $(this).serialize();
$.post('/endpoint', data, function(data) {
// some logic here
});
});
Symfony 4+에서는 컨트롤러나 작업에 바로 의존성 주입을 사용할 수 있습니다. 예를 들어 양식을 제출하고 같은 양식의 토큰을 새로 고치고 싶다면,$tokenId
는 폼 유형 클래스의 FQDN입니다.
namespace App\Controller;
use App\Form\MyFormType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
class MyController extends AbstractController
{
public function submit(CsrfTokenManagerInterface $tokenManager): JsonResponse
{
// ...
$token = $tokenManager->refreshToken(MyFormType::class);
return new JsonResponse(['token' => $token->getValue()]);
}
}
그리고 자바스크립트에서는 기존 토큰을 업데이트 할 수 있습니다.<input>
.
const token = document.getElementById('_token');
fetch(url, opts)
.then(resp => resp.json())
.then(response => {
if (response.token) {
token.value = response.token;
}
});
언급URL : https://stackoverflow.com/questions/12054449/symfony-csrf-and-ajax
'sourcecode' 카테고리의 다른 글
PowerShell에서 Write-Debug 출력을 콘솔에 표시하려면 어떻게 해야 합니까? (0) | 2023.10.31 |
---|---|
변수의 대문자 첫번째 문자 (0) | 2023.10.31 |
how to toggle attr() in jquery (0) | 2023.10.31 |
콘솔에서 프로그램이 실행되는지 확인하는 방법은 무엇입니까? (0) | 2023.10.26 |
mysql 쿼리에서 일련 번호 생성 (0) | 2023.10.26 |