2
votes

I use Laravel as a REST API - communicating with a SPA over on another domain.

I need help in sending the CSRF token over to my app.

I cannot echo it inside a hidden field, since my SPA is on another domain.

Can I place the CSRF token inside a cookie?

How can I do it?

I could send it through a get request - but I'm not sure it's safe.

Note: to be clearer, I'm thinking of sending the token inside a cookie, on my very first Get request.

Thank you!

1
Guys, what are your takes... is it safer to send the token through a cookie than directly through the JSON response - in this scenario? - Dany D

1 Answers

2
votes

Just use the function csrf_token() to create your cookie.

$tok = Cookie::make('token', csrf_token(), 30);
return Response::make('tadaaam')->withCookie($tok);

Or use it like this to append to a view.

$view = View::make('home');
$tok = Cookie::make('token', csrf_token(), 30);
return Response::make($view)->withCookie($tok);

To validate you should add a new filter.

Route::filter('csrfcookie', function()
{
    if (Session::token() != Cookie::get('token'))
    {
        throw new Illuminate\Session\TokenMismatchException;
    }
});