dlook's avatar
Level 4

TokenMismatchException - Posting from outside of Laravel

I need to create sort of an API endpoint that will receive POST json data from other site via AJAX.

I know inside the confines of Laravel I can use csrf_field() or csrf_token() but what about creating POST routes as an API that will be posted from other sites/apps? I'm also getting cross origin error, is there a normal way to allow route to become an API endpoint or we need additional custom packages to make the CORS work?

EDIT: I know I can add it to $except array in VerifyCsrfToken.php, but is there more pragmatic way to do it?

0 likes
5 replies
tykus's avatar

CSRF verifies that a request has come from your site; an API is, by design, not going to want or need to do that .

ollyc1804's avatar

@dlook As far as I'm aware the best way to achieve this is to add your route (or a wildcard for your routes) to the $except array

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
    ];
}

and then authenticate that the source posting to those endpoints are trusted by you with a generated api key sent in the HTTP headers. Correct me if I'm wrong @tykus.

Note: You will want to make sure your app has an SSL cert if you are posting sensitive data like passwords or api keys.

Snapey's avatar

use the API routes (L5.3/5.4) They are designed just for this and exclude sessions and CSRF

tykus's avatar

@ollyc1804 the point I was making was that discussion of CSRF in the context of an API is moot.

Please or to participate in this conversation.