Laravel 5.4 Api Route 401

21,508

It doesn't work because your route is protected by auth:api, which returns 401 unauthorized. The only way to go through auth:api is to send your authentication token with every single request

var token = <?php json_encode(Auth::user()->api_token); ?>; //if you are using api_token

$.ajax({
    url: 'api/postStream',
    headers: {
        'Authorization':'Bearer ' + token,
    },
    type: 'post',
    ...
});

The way you get your token is entirely up to you. You could use Passport or simply the easiest solution which is adding api_token to your users table.

If you are going for the cheapest solution, you can follow this post: https://gistlog.co/JacobBennett/090369fbab0b31130b51

Share:
21,508
utdev
Author by

utdev

Name: Umut Tufanoglu Currently working at: adesso.

Updated on April 08, 2020

Comments

  • utdev
    utdev about 4 years

    I built a new laravel 5.4 project.

    I tried to do the steps below in my api route, but somehow they do not work.

    In my app.js file I have this ajax call:

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
        }
    });
    $.ajax({
        url: 'api/postStream',
        type: 'post',
        data: { imgData: imgData },
        success:function(data) {
            console.log('success');
        }
    });
    

    My Api Route looks like this:

    Route::group(['middleware' => 'auth:api'], function()
    {
        Route::post('postStream', ['as' => 'image', 'uses' => 'ApiController@postStream']);
    });
    

    And my controller:

    public function postStream(Request $request)
    {
        $imgData = $request->imgData;
        ...
    }
    

    But I get this error in my chrome dev console:

    POST http://localhost/app/public/api/postStream 401 (Unauthorized)
    

    And in the network tools this:

    {error: "Unauthenticated."}
    error
    :
    "Unauthenticated."
    

    I guess I am somewhat not authentificated, but I do not know how to make that happen this way.