0
votes

showing {"error":"Unauthenticated."}, while calling larvel API in Laravel 5.4 and passport version: v1.0.9, using ajax call.

Calling from route api: Route::get('category/get_tree_data', 'CategoryApiController@getTreeData')->middleware('auth:api');

4

4 Answers

1
votes

If you set up Laravel Passport properly, you should have this in your view:enter image description here

You need to create a client, that client has a client id and a client secret.

Now you need to open your consumer app which shall contain your client id and your client secret.

It looks like this(you have to change the token and id to your specific one):

class OAuthController extends Controller
{
    public function redirect()
    {
        $query = http_build_query([
            'client_id' => 3,
            'redirect_uri' => 'http://localhost/app/public/callback',
            'response_type' => 'code',
            'scope' => '',
        ]);

        return redirect('http://localhost/app/public/oauth/authorize?' . $query);
    }

    public function callback(Request $request)
    {
        $http = new Client;

        $response = $http->post('http://localhost/app/public/oauth/token', [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'client_id' => 3, // from admin panel above
                'client_secret' => 'BcTgzw6YiwWUaU8ShX4bMTqej9ccgoA4NU8a2U9j', // from admin panel above
                'redirect_uri' => 'http://localhost/app/public/callback',
                'code' => $request->code // Get code from the callback
            ]
        ]);

        return json_decode((string) $response->getBody(), true);
    }
}

Now you need to call that consumer app and authorize your application.

enter image description here

If that worked you get an access token + a refresh token.

It should look like this:

enter image description here

Now you can test this using a program like postman.

You basically call your get route and add the access token, which gives you access to the api, like this:

enter image description here

If you have any more question I recommend reading the docs.

Thus I highly recommend watching following video from Taylor Otwell.

Of course you can give me a comment aswell if you have any more questions.

0
votes

Add this code inside your /resources/assets/js/bootstrap.js file

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
    'X-Requested-With': 'XMLHttpRequest'
};

working perfectly...

0
votes

I have the same issue with Laravel 5.8 when calling /api/user on auth:api middleware, I've tried to call the API url using Postman but got unauthenticated message

And I am able to fixed it by changing the hash value to false in config/auth.php file

// routes/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
// config/auth.php
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false, // <-- change this to false
        ],
    ],
0
votes

I faced the same issue.

In my case, I was caching generated token after user login.


$token = $user->createToken('API'.'-'.strtoupper($user->username).'-'.'-X-AUTH-TOKEN', [$this->scope]);

Cache::add(strtoupper($user->username).'-'. 'X-TOKEN', $token->accessToken, $expiresAt);

After debugging, tried clearing cache


Cache::clear();

and it's working now.