Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DBos's avatar
Level 1

CSRF protection not working

I am currently building a Laravel app that uses Angular for some parts of the frontend. Now I noticed that Laravel's CSRF protection is not working correctly when I am submitting forms via Angular.

My Angular form submit looks basically like this:

$http.post(appUrl + '/name', {
    name: name
}).then(function (response) {
    console.log(response.data);
});

In my web.php routes file I route the post request to /name to a controller method that looks like this:

public function postName() {
    return response()->json([
        'lorem' => 'ipsum'
    ]);
}

Now if I run the post submit, the method's response is being logged in my browser's console. I am wondering why this is, since nowhere I am sending a CSRF token. If I try to submit the form to the same route without Angular the expected TokenMismatchException will be thrown.

Nowhere in my code I am sending a CSRF token with the Angular POST request, so it basically should throw a TokenMismatchException. What is the problem here?

0 likes
8 replies
Snapey's avatar

Is the route in your api.php routes file or web.php?

I ask because routes in api.php don't have sessions and therefore don't have csrf token checking

DBos's avatar
Level 1

Thank you for your reply!

I am aware of that. The route is set up in the web.php file. I also confirmed with php artisan route:list that the route has the web middleware.

Like I said, when posting the form directly instead via Angular the Exception is thrown correctly.

Snapey's avatar

So is angular picking it up from the meta tag in the html page header.

DBos's avatar
Level 1

I had the same idea and removed the tag for testing purposes. Still no exception is thrown.

Snapey's avatar
Snapey
Best Answer
Level 122

You can see if the csrf token is being sent by looking at the network request in your browser developer tools

DBos's avatar
Level 1

I feel like such a fool. A token is actually being sent. I don't know how, but it is. So after all the CSRF protection was working correctly.

Thanks for your help!

Snapey's avatar

Laravel 5.4 tries to cover it all ways

with a metatag

    <!-- CSRF Token -->
    <meta name="csrf-token" content="2rLh5i78Rga39Rk8rSZxFJLchO8rejx1nTvFnIkZ">

and a script tag

    <script>
        window.Laravel = {"csrfToken":"2rLh5i78Rga39Rk8rSZxFJLchO8rejx1nTvFnIkZ"};
    </script>

It must be one of these surely?

1 like
DBos's avatar
Level 1

Yet it really isn't. I even checked if something like that was dynamically added but it isn't. Still for some reason a valid CSRF token is send with the request.

Anyway, I am happy that everything is working as it should.

Please or to participate in this conversation.