Skip to content

Using IsCsrfTokenValid attribute with invalid token redirects user to login page #57343

Open
@cyve

Description

@cyve

Symfony version(s) affected

7.1.1

Description

Hi,
I tried the new IsCsrfTokenValid attribute on a route to handle a form. When the token is invalid, the user is redirected to the login page instead of an error page. Probably because IsCsrfTokenValidAttributeListener throws a InvalidCsrfTokenException witch extends AuthenticationException.

How to reproduce

Add IsCsrfTokenValid attribute on a route handling a form

#[Route('/add-to-cart', name: 'add_to_cart', methods: ['POST'])]
#[IsCsrfTokenValid('add_to_cart')]
public function __invoke(Request $request): Response
{
}

Load the page and wait for the token to expire (or generate an invalid token)

<form method="post" action="{{ path('add_to_cart') }}">
  <input type="hidden" name="product" value="{{ product.id }}">
  <input type="hidden" name="_token" value="this_token_is_invalid">
</form>

Possible Solution

Maybe we could throw a BadRequestHttpException instead of an InvalidCsrfTokenException in IsCsrfTokenValidAttributeListener ? But I guess there is a good reason for InvalidCsrfTokenException to extend AuthenticationException, so I can't really see the implications.
If this solution looks good to you, I can create a PR.

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions