8

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.

enter image description here

  • hi did you found a solution yet? – utdev Apr 06 '17 at 13:04
  • @utdev Sadly not. Did you do in the meantime? Thanks in advance. –  Apr 19 '17 at 19:56
  • Either provide authentication details (token) or remove the middleware? – Martin Bean Apr 19 '17 at 20:00
  • I may have found a solution today but currently I am not on my dev machine so I may answer tomorrow (or at least give some advice) – utdev Apr 19 '17 at 20:10
  • maybe you just want an `auth` middleware for web authentication instead `auth:api` which is used for public API that needs auth token. – Bagaskara Wisnu Gunawan Apr 26 '17 at 09:08
  • if you are using **laravel/passport** you can consume your own Api. [laravel passport documentation]https://laravel.com/docs/5.4/passport#consuming-your-api-with-javascript in which case a temporary access token is created with each successful session validation which authenticates the Api calls. – Ashutosh Raj Apr 26 '17 at 18:32
  • Otherwise you need to pass the access token and then include in the api call for authentication. Alternatively you dont use the api calls and make the routes in web router and use the auth:web as the authentication route which will depend on the sessions and wont be a session less API calls. – Ashutosh Raj Apr 26 '17 at 18:43

4 Answers4

3

The point is you aren't authenticated. The CSRF Token isn't an authentication token.

You will need a way of authenticating your users against the api and (for example) give them an unique auth token, which they send with each request, in order to be sure they are allowed to use your API.

Maybe this link may be helpful:

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

This part of the docs maybe helpful too. It's about HTTP basic authentication:

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

Especially the part "Stateless HTTP Basic Authentication"

ExCluSiv3
  • 98
  • 1
  • 7
1

Let's take a look at the HomeController construct method. Is there a call that looks something like this?

$this->middleware(['auth']);
Dharmesh Rakholia
  • 1,210
  • 9
  • 22
0

I have two solutions:

  1. Create a controller without using the auth middleware: $this->middleware(['auth']);

  2. Creating the route before the Route::group(['middleware' => 'auth'] in the routes/web.php file.

enter image description here

0

you can add the 'api_token' attribute and field to the table user, in this case will use the Bearer token option:

you can use this documentation:

https://laravel.com/docs/5.8/api-authentication

and then using jquery, adding the 'Authorization' header, will be:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
        'Authorization': 'Bearer {{Auth::user()->api_token}}'
    }
});