Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

296
Vistas
Laravel 5.4 + Ajax equals 401 Unauthenticated

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

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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"

about 4 years ago · Santiago Trujillo Denunciar

0

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

$this->middleware(['auth']);
about 4 years ago · Santiago Trujillo Denunciar

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

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda