Skip to content

Commit dd17264

Browse files
committed
Add CSRF protection to logout url in the user controller
1 parent 28ca5c5 commit dd17264

File tree

3 files changed

+8
-4
lines changed

3 files changed

+8
-4
lines changed

config/services.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ services:
3434
App\EventSubscriber\CommentNotificationSubscriber:
3535
$sender: '%app.notifications.email_sender%'
3636

37+
Symfony\Component\Security\Http\Logout\LogoutUrlGenerator: '@security.logout_url_generator'
38+
3739
when@test:
3840
services:
3941
test.user_password_hasher:

src/Controller/UserController.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
use Symfony\Component\HttpFoundation\Response;
2121
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
2222
use Symfony\Component\Routing\Annotation\Route;
23+
use Symfony\Component\Security\Http\Logout\LogoutUrlGenerator;
2324

2425
/**
2526
* Controller used to manage current user.
@@ -52,7 +53,7 @@ public function edit(Request $request, EntityManagerInterface $entityManager): R
5253
}
5354

5455
#[Route('/change-password', methods: ['GET', 'POST'], name: 'user_change_password')]
55-
public function changePassword(Request $request, UserPasswordHasherInterface $passwordHasher, EntityManagerInterface $entityManager): Response
56+
public function changePassword(Request $request, UserPasswordHasherInterface $passwordHasher, EntityManagerInterface $entityManager, LogoutUrlGenerator $logoutUrlGenerator): Response
5657
{
5758
$user = $this->getUser();
5859

@@ -63,7 +64,7 @@ public function changePassword(Request $request, UserPasswordHasherInterface $pa
6364
$user->setPassword($passwordHasher->hashPassword($user, $form->get('newPassword')->getData()));
6465
$entityManager->flush();
6566

66-
return $this->redirectToRoute('security_logout');
67+
return $this->redirect($logoutUrlGenerator->getLogoutPath());
6768
}
6869

6970
return $this->render('user/change_password.html.twig', [

tests/Controller/UserControllerTest.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,10 @@ public function testChangePassword(): void
9090
'change_password[newPassword][second]' => $newUserPassword,
9191
]);
9292

93-
$this->assertResponseRedirects(
93+
$this->assertResponseRedirects();
94+
$this->assertStringStartsWith(
9495
'/en/logout',
95-
Response::HTTP_FOUND,
96+
$client->getResponse()->headers->get('Location') ?? '',
9697
'Changing password logout the user.'
9798
);
9899
}

0 commit comments

Comments
 (0)