CSRF Protection Part 2

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

The only tricky thing is that we only want to require the Content-Type header when the user is requesting an API endpoint. In our application, this means all the endpoints inside of RepLogController. So, we could see if the URL starts with /reps... but that could get ugly later if the API grows to a lot of other URLs.

If your app is entirely an API, that's easy! Or if all the URLs start with /api, that's also easy to check.

But, in our app, let's use a different trick... which is gonna be kinda fun.

Above the controller class, add @Route() with defaults={} and a new flag that I'm inventing: _is_api set to true.

... lines 1 - 13
... line 15
* @Route(defaults={"_is_api": true})
class RepLogController extends BaseController
... lines 19 - 101

When you put an @Route annotation above the controller class, it means its config will be applied to all of the routes below it. Now, inside of the subscriber, we can read this config. To see how, add dump($request->attributes->all()) then die.

... lines 1 - 9
public function onKernelRequest(GetResponseEvent $event)
... lines 12 - 16
... lines 18 - 22
... lines 24 - 32

If you refresh the main page... no _is_api here. But now go to /reps. There it is! Any defaults flags that we set are available in $request->attributes.

Creating a Custom ApiRoute Annotation

The only problem is that this syntax is... oof... gross. Let's make it easier. In the Api directory, create a new PHP class called ApiRoute. Make this extend the normal Route annotation class.

Yep, we're creating a brand new, customized route annotation. Add @Annotation above the class.

... lines 1 - 6
* @Annotation
class ApiRoute extends Route

If we did nothing else, we could at least go into our controller and use it: @ApiRoute().

... lines 1 - 14
... line 16
* @ApiRoute(defaults={"_is_api": true})
class RepLogController extends BaseController
... lines 20 - 102

Try it! Nothing changes. But now, in ApiRoute, go to the Code -> Generate menu - or Command+N on a Mac - and override the getDefaults() method. Return a merge of _is_api set to true and parent::getDefaults().

... lines 1 - 11
public function getDefaults()
return array_merge(
['_is_api' => true],
... lines 19 - 20

Nice, right? Back in the controller, remove the ugly defaults stuff. Oh, and if you want to mark just one route as an API route, you can also use this new annotation above just one method.

Ok, go back and refresh! Got it!

Validating the Content-Type Header

Back in the subscriber, remove the dump. Then, if !$request->attributes->get('_is_api') return. And now that we know were only operating on API requests, check the header: if $request->headers->get('Content-Type') does not equal application/json, we have a problem! Create a new 400 response: $response = new JsonResponse().

The data we send back doesn't matter - I'll add a message that says what went wrong. But, give this a 415 status code: this means "Unsupported Media Type". Finish this with $event->setResponse($response). This will completely stop the request: this response will be returned without even calling your controller.

... lines 1 - 10
public function onKernelRequest(GetResponseEvent $event)
... lines 13 - 23
if (!$request->attributes->get('_is_api')) {
if ($request->headers->get('Content-Type') != 'application/json') {
$response = new JsonResponse([
'message' => 'Invalid Content-Type'
], 415);
... lines 38 - 46

Ok, let's try this! Find the rep_log_api.js file and look down at createRepLog. We are setting this Content-Type header. So, this should work! Move over, go back to /lift and refresh. I'll open my network tools. And.. yea! It totally works! But try to delete a rep log... failure! With a 415 status code.

Always Sending the Content-Type Header

This is because the DELETE endpoint does not set this header. And... hmm, it's kinda weird... because, for the DELETE endpoint, the body of the request is empty. There's some debate, but, because of this, some people would argue that this request should not need any Content-Type header... because we're not really sending any JSON!

But, by requiring this header to always be set, we give our application a bit more security: it removes the possibility that's somebody could create a CSRF attack on that endpoint... or some future endpoint that we don't send any data to.

In other words, we are always going to set this header. Remove it from createRepLog and go up to fetchJson() so we can set this here. The only tricky thing is that it's possible that someone who calls this will pass a custom header, and we don't want to override that.

Add let headers = and set this to the Content-Type header. Then, if options && options.headers - so, if the user passes a custom header, merge them together: headers = , ...options.headers then ...headers. Then, delete that property and, below, pass headers to headers.

function fetchJson(url, options) {
let headers = {'Content-Type': 'application/json'};
if (options && options.headers) {
headers = {...options.headers, ...headers};
delete options.headers;
return fetch(url, Object.assign({
... line 9
headers: headers,
}, options))
... lines 12 - 17
... lines 19 - 53

Try it! Move over - looks like the page already refreshed. And... yes! We can delete again!

And we are protected from CSRF! That's because, first, we do not allow other domains to make AJAX calls to our site and, second, all of our API endpoints require a JSON body - which we explicitly required by looking for the Content-Type header.

Oh my gosh.... we're done! That's it, that's everything! If you've made it all the way through, you rock! You have the tools to create the craziest frontend you can think of! And yes, there are more things in React that we could cover, like the React router or Redux, which adds a more complex architecture on top of React, but helps solve the problem of passing around so many props.

But, these are extras - go get some real-world success with React and report back! We'd love to know what you're building.

Alright people, seeya next time.

Leave a comment!

  • 2019-11-12 Caglar

    Do it!!!!!

  • 2019-09-12 Johnny Lattouf

    Thank you :)

  • 2019-07-10 R R


  • 2019-06-25 Diego Aguiar

    Hey Skylar Scotlynn Gutman

    Probably PhpStorm Symfony plugin is not smart enough to read those annotations as a Symfony Route. Try re-indexing your project after that change if it doesn't work you may have to tweak some config in order to make it to work


  • 2019-06-25 Diego Aguiar

    Hey Brizzz

    Sorry for the late response. Somehow I missed this comment

    Indeed you are right, that code works but it only works because we have installed babel-plugin-transform-object-rest-spread library


  • 2019-06-25 Skylar Scotlynn Gutman

    Hey guys,

    Thanks for the awesome resource.

    When I implement @ApiRoute, PhpStorm gets angry. $this->generateUrl('routename' says missing route. Do you get the same result?

  • 2019-06-17 weaverryan

    Hey Tobias Ingold@

    This is definitely on our radar - especially as we get more into API's etc. What I *can* tell you is that, about the hardcoding, i wouldn't worry about it. We *do* hardcode routes increasingly, because we're thinking of our API as its own "standalone" thing and our frontend as its own "standalone" thing. URLs then become a sort of "contract", where your API "promises" not to change them and then your frontend can hardcode them (this is exactly how the world works when the API and user of an API are not the same "app"). This just forces you to "think" before changing any URLs (similar to how you would "think: before renaming any methods in your code): if you update a URL in your API, you just need to find and update it on the frontend. You *can* also use FOSJsRoutingBundle, if this really bothers you :).

    Sorry I don't have anything more ready to tell you than that right now! But this is a general direction that we're moving, of course, with our tutorials.


  • 2019-06-13 Tobias Ingold

    I would looooove you guys if you did a course on single page apps using symfony and react. I am struggling with the idea of hardcoding routes when using react router, and I'm not sure how to let react take care of the front end while still leaving my api routes untouched.
    Would be awesome if you could make a screencast about that stuff because it's super interesting and fun, and also, this screencast made me fall in love with react :D

  • 2019-06-07 Skylar Scotlynn Gutman

    +1 for Redux

  • 2019-05-03 Brizzz

    Or... we can fix it like that:
    headers = {...options.headers, ...headers};

  • 2019-03-21 Diego Aguiar

    Hey Samuel Weber

    You are totally right! Looks like Ryan managed it like if it were an array, the right approach is using Object.assing({}, obj1, obj2); as you mentioned it.


  • 2019-03-21 Samuel Weber

    Hello everyone,
    headers = {...options.headers, headers};
    doesnt work for me when I add a header in one of the exported api-methods

    it results in following headers-Object:

    If I use
    headers = Object.assign({}, options.headers, headers);
    everything works fine.

    I used this method to test:

    export function createRepLog(repLog) {
    return fetchJson('/reps', {
    method: 'POST',
    body: JSON.stringify(repLog),
    headers: {foo:'BAR', 'Content-Type': 'plain-text'}

    The console-output for the fetch-request:

    POST http://react-course/reps 415 (Unsupported Media Type)

    I am kinda confused ;-)

    let a = { foo: 'bar' };
    let b = { foz: 'baz' };
    console.log(JSON.stringify({...a, b}));

    results in:


    thanks in advance and thank you for your _awesome_ tutorial!

    greetz Sam

  • 2019-02-25 weaverryan

    Hey Bart!

    Ah, this was a tricky one! But.. it IS working ;). It comes down to one small detail. You currently have:

    * @ApiRoute()
    * @Route("/stories/{slug}", name="stories_slug_set", methods={"POST"})
    public function setStory()

    The result is that this created TWO routes - you can see them if you run php bin/console debug:router:

    -------------------- -------- -------- ------ --------------------------
    Name Method Scheme Host Path
    -------------------- -------- -------- ------ --------------------------
    app_story_setstory ANY ANY ANY /
    stories_slug_set GET ANY ANY /stories/{slug}

    The FIRST one comes from the ApiRoute, and it DOES have the _is_api default. The second is just a normal route. Basically, you should use ApiRoute *instead* of Route, not along with it. Both Route and ApiRoute create routes. In your case, you've created two routes - one that is an "api route" and one that is a normal route. Try this instead:

    * @ApiRoute("/stories/{slug}", name="stories_slug_set", methods={"POST"})
    public function setStory()

    Let me know if that works!


  • 2019-02-22 Diego Aguiar

    Wow, you are right, this is not working on methods. This might be a Symfony's bug. I'll ask Ryan about this
    Thanks for sharing your case :)

  • 2019-02-22 Bart

    The code is visible at https://bitbucket.org/bschutte/apiroute/src/master/ Hopefully this allows you to spot the problem :) Alternatively you could check out the repo and have a look at which is a test page on which you can reproduce the problem

  • 2019-02-19 Diego Aguiar

    Hmm, it only works when you use it on the entire class? That's odd. I may have to see your code, if you can upload it to Github or somewhere else

  • 2019-02-17 Bart

    Thanks for your reply Diego Aguiar :) I'm positive I'm extending the correct class, it's just that when I use the @ApiRoute() annotation it doesn't work above a single method, it only works above the entire class. Ryan points out in the video it should work with just a single method?

  • 2019-02-15 Diego Aguiar

    Hey Bart

    Which URL are you accessing? Remeber that it only works on RepLogsController routes. Oh, and can you double check that your ApiRoute extends from the right Symfony Route class?


  • 2019-02-14 Bart

    Hi Guys :) I've been trying to follow along for this chapter but I'm a bit stuck :(

    It's the ApiRoute.php class. I've created it and I'm trying to use it now as an annotation above the route in my controller like so:

    * @ApiRoute()
    * @Route("/stories/{slug}", name="stories_slug_set", methods={"POST"})

    But symfony seems to ignore it. When I try to dump($request->attributes->all()) , the _is_api key is not there. When I use `@Route(defaults={"_is_api": true})` however, it is there!

    Weird thing is, I tried to use the exercise files as a reference and check if I had missed something somewhere, but inside the finish folder the ApiRoute.php class file seems to be missing entirely? Hopefully you can help me out :)

  • 2018-12-13 mouerr

    +1 for Redux

  • 2018-10-26 Ivan Puntiy

    +1 for Redux

  • 2018-08-24 weaverryan

    Hey Askan Simon!

    Ah! So if you want external programs to use your API, that's different. That IS a more appropriate use-case for having API tokens. What I'd recommend is *two* authenticators: one for the normal, session-based authentication and another that allows token-based authentication. Then, you can use the session-based login for your JavaScript app and allow the external applications to send an API token.

    If you have some more questions about this, I'd be happy to answer :).


  • 2018-08-23 Askan Simon

    Dear weaverryan, thank you very much for your detailed answer.
    I thought lot about it and came to similar conclusions,
    and have rebuilt the app sessionbased like in your tutorial.
    But there is a disadvantage. How can I share the Api with
    other programs, that do not use the frontend? I think
    a new Route ("apiextern") and in additional authorisation
    etc. is the solution ;) Best Regards Askan

  • 2018-08-20 weaverryan

    Hey Askan Simon!

    Great question :). Your first option is ... don't use API keys! Just use session-based storage and cookies like we do in this tutorial. It's simple & secure (as long as you have your user use HTTPS, which you always should). But yes, I see you are already using API keys ;).

    The issue with API tokens is where to store them? And, honestly, there's a lot of conflicting info about this. For example: https://dev.to/rdegges/plea... - according to this resource, using local storage is not an option (though it would be really simple!). Other places - https://auth0.com/docs/secu... (which is a great site I trust) - absolutely show local storage being used - they even show it in their quick starter docs: https://auth0.com/docs/quic...

    So... there is clearly some security issues with using local storage... though *how* big of a deal, is debated :/. You're right that putting the API key as a global JavaScript variable is not a good idea. Well, it's actually the same as "local storage" - other JavaScript running on your page could access it.

    So, use local storage... or if you really care about security, use sessions & cookies :). That's probably not the exact answer you wanted, but that's the state of things :).


  • 2018-08-18 Askan Simon

    Hello. Thank you for the great tutorial. I already had an API with ApiKeys:
    everything works great. But I do not want to build a Single Page Application,
    how can React remember the ApiKey between two page views? I think it's not
    so good to hand it over via Twig ;) (I am a beginner with React...) Thank you

  • 2018-08-17 weaverryan

    Hey Matt Johnson!

    Dude, you're 100% correct! This one still makes my head hurt... so I don't use it... yet. But, there have been many other ES6 things that I once did not like, and now love ;).

    Glad you like the tutorial!


  • 2018-08-17 Matt Johnson

    Awesome, great tutorials!

    FYI with ES6 you don't have to add an object key when adding a variable to an object, so long as that variable's name matches the key. So in this case instead of

    credentials: 'same-origin',
    headers: headers
    }, options)

    You can just put:

    credentials: 'same-origin',
    }, options)

    Does the same thing!

  • 2018-08-16 weaverryan

    Hey Milan Vlach!

    You're just *barely* too early - the video is posted now :). And, I'm *thrilled* you found the course useful - I had such a great time writing it with Franks help! And yes, Redux is absolutely something we're thinking about... it's not a certainty yet... we're waiting to see more people ask for it. However, this tutorial has been very well-received, so I think there will be good demand to keep going with Redux.


  • 2018-08-15 Milan Vlach

    Cool guys!

    I am a little bit too soon here, but that is because you made such a great course which I have been returning to every day! What a ride! Are you planning on adding Redux course too? You could call it something like: "JavaScript for PHP Geeks: Redux for the legends (with symfony)". :imagine_sun_glasses_emoji_here: