Skip to content
This repository was archived by the owner on Sep 23, 2022. It is now read-only.

csrf protected links

Jérôme Tamarelle edited this page May 12, 2013 · 7 revisions

You can send unsafe requests to your application using links (a tags), by enabling the csrf_links option in your config.

# app/config/config.yml
knp_rad:
    csrf_links:
        enabled: true

This will allow you to use twig functions that generate html attributes on your links

link_attr('delete', 'Are you sure you want to delete object ...?')
link_attr('patch') // will ask confirmation with default message "Are you sure?"
link_attr('put', false) // no confirm
link_csrf()

Those attributes will be used later by an unobstrusive javascript jquery plugin to create the corresponding requests.

To use this javascript, use the base RadBundle layouts, or include it yourself using:

    <script type="text/javascript" src="{{ asset('/bundles/knprad/js/jquery-ujs.js') }}"></script>

For example:

    <a href="{{ path('app_blogposts_delete', {'id': id}) }}" {{ link_attr('delete', 'Are you really sure ?') }}>Delete</a>

Thats' it! Your link will create a valid DELETE request, protected from csrf, with a confirmation box.

You can do that with PUT, POST and PATCH too.

Example:

    <a href="{{ path('app_blogposts_toggle_visibility', {'id': id}) }}" {{ link_attr('patch', false) }}>Toggle visiblity</a>

You still can generate those attributes by hand using:

    <a href="{{ path('app_blogposts_toggle_visibility', {'id': id}) }}" data-method="post" data-csrf-token="{{ link_csrf() }}">Toggle visiblity</a>
Clone this wiki locally