Whenever I try to assign a route from my api.php
File I get a 401: Unauthenticated
-Error.
This is the route:
Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function () {
Route::post('admin/product-image-sort', 'ApiController@SaveProductImageSort')->name('api.save-product-image-sort');
});
Im calling this using Jquery Ajax:
<script>
$('#sortable-image-container').sortable({
items: '> .row > *',
update: function (event, ui) {
var data = $(this).sortable('serialize');
console.log(data);
$.ajax({
data: data,
type: 'POST',
url: "{{ route('api.save-product-image-sort') }}",
success: function (data) {
if(data == "success"){
$.notify({
icon: 'pe-7s-close-circle',
message: "Sucessfully saved the Image Sorting"
},{
type: 'success',
timer: 500
});
}
}
});
}
});
</script>
So this works flawless when excluding the 'middleware' => 'auth:api'
part but I don't want to just allow accessing my internal api without any form of authentication.
What the api does is send an array of ids it got using a serialization of jQuery Ui's Sortable. The ApiController then foreachers through that and updated the sorting of every image of a specific product.
I've included the CSRF Token like stated in the Laravel Docs by putting csrf_token()
into a meta-tag and attaching it to every Ajax request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
As I can also see in Chrome's network tab is that it adds two cookies to the request.