Laravel 5.4 + Ajax等于401 Unauthenticated

PoT*_*Tii 7 ajax jquery csrf http-status-code-401 laravel-5

每当我尝试从我的api.php文件中分配路由时,我得到一个401: Unauthenticated-Error.

这是路线:

Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function () {
    Route::post('admin/product-image-sort', 'ApiController@SaveProductImageSort')->name('api.save-product-image-sort');
});
Run Code Online (Sandbox Code Playgroud)

我使用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>
Run Code Online (Sandbox Code Playgroud)

因此,在排除'middleware' => 'auth:api'部件时这可以完美无缺,但我不想仅仅允许在没有任何形式的身份验证的情况下访问我的内部api.

api做的是发送一个使用jQuery Ui的Sortable序列化得到的id数组.然后,ApiController通过它进行预测并更新特定产品的每个图像的分类.

我通过放入csrf_token()元标记并将其附加到每个Ajax请求中来包含像Laravel Docs中所述的CSRF令牌:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
}); 
Run Code Online (Sandbox Code Playgroud)

正如我在Chrome的网络标签中看到的那样,它为请求添加了两个cookie.

在此输入图像描述

小智 3

关键是你没有经过身份验证。CSRF 令牌不是身份验证令牌。

您将需要一种方法来根据 api 对用户进行身份验证,并(例如)为他们提供一个唯一的身份验证令牌,他们随每个请求发送该令牌,以确保他们被允许使用您的 API。

也许这个链接可能有帮助:

https://laracasts.com/discuss/channels/laravel/53-api-routes-auth-middleware-confusion

文档的这一部分可能也有帮助。这是关于 HTTP 基本身份验证的:

https://laravel.com/docs/5.4/authentication#http-basic-authentication

特别是“无状态HTTP基本身份验证”部分