Laravel post JSON using CSRF Protection

- 1 answer

Ad

I'm starting with Laravel 5, and I want do everything right. I'm doing "Post" with Json, and I wanna implement CSRF Protection but I don't know how can I do that on my JSON. I saw so many examples with AJAX but with JSON I didn't found none.

I need to set manually every token for person or laravel do that automatically?

How can i pass token as argument on that JSON ?

That is my JSON:

{
   "foo":"bar"
}

That's my controller code:

public function Register()
{
    $teste = Request::json()->all();
    return  $teste;    
}

I'm using all protection default from Laravel on middleware.

Ad

Answer

Ad

You always need to pass the CSRF token, whether posting with ajax or normally. This is basically a security feature.

Laravel generate it automatically.

You need to create "_token" variable on your page, You can create the variable once also in the main template and then you can access it in the whole project:

<script type="text/javascript">
    var secure_token = '{{ csrf_token() }}';
</script>

Now you can send the token with data in the ajax calls like below:

$.ajax({
    data: { _token: secure_token }
});

If you are posting any data through form submission you can post it like:

<input type="hidden" name="_token" value="{{ csrf_token() }}">

You should always have the CSRF token posted with every ajax request or form submission you make within your project.

Ad
source: stackoverflow.com
Ad