Question: Angular2 and Laravel CSRF protection

Question

Angular2 and Laravel CSRF protection

Answers 1
Added at 2016-12-19 10:12
Tags
Question

I have already read some topics

And the problem I encountered is lies in this piece of code

<meta property="csrf-token" name="csrf-token" content="{{ csrf_token() }}">

I'm using Angular2 as core engine, which sending AJAX requests to Laravel API and I'm not using blade templates - just .html files, so I can't call php function csrf_token() from html file

So, I added a temporary solution by extending my /var/www/pandacrm/app/Http/Middleware/VerifyCsrfToken.php file

public function handle($request, Closure $next)
{
    if ( ! $request->is('api/*'))
    {
        return parent::handle($request, $next);
    }

    return $next($request);
}

But it seems not the best way to work around, is there any other solutions to resolve this issue?

Answers to

Angular2 and Laravel CSRF protection

nr: #1 dodano: 2016-12-20 05:12

You can create a meta tag with csrf-token content by using JavaScript in your html file!

Just send an Ajax request to Laravel Route to get token. (return token in a Controller action.)

and then create a meta tag with that token inside.

but you have to disable csrf protection on that specific route, first.

There is a way to do this here for laravel5 or here for 5.3

Now you have a meta tag with csrf, that can be used for other requests.

Source Show
◀ Wstecz