Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Passport "auth:api" middleware acts as "web, auth" middleware

I have set up the Laravel Passport package for Laravel 5.3 just as described in the official documentation (https://laravel.com/docs/5.3/passport#introduction).

I want the API to be consumed by a mobile application, so I am trying to implement Password Grant Tokens. I have created a password grant client, and the token request process...

$response = $http->post('http://my-app.com/oauth/token', [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'username' => '[email protected]',
        'password' => 'my-password',
        'scope' => '',
    ],
]);

...Just works as expected, returning an access-token and a refresh-token for one of my users.

On the one hand,

php artisan route:list

Lists correct middleware for api/user URI: api,auth:api

And driver for api guard is correctly set to passport in config/auth.php. Summing up, every step of the installation process has been done (https://laravel.com/docs/5.3/passport#installation).

Defaults contents of api.php:

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

The problem comes when I access to http://my-app.com/api/user, because it seems it is authenticating the request using the 'web' middleware, not the 'api'... When I access, I am redirected to /login (login form) if the user was not logged in, and to /home if it was...

Any help would be really appreciated. Thanks in advance.

like image 931
andcl Avatar asked Nov 10 '16 00:11

andcl


1 Answers

Solved! Just for the record, the solution:

I was sending the request to http://my-app.com/api/user with HTTP Header wrong. I was sending:

Type: Authorization - Content: Bearer: $accessToken 

...and the correct way was:

Type: Authorization - Content: Bearer $accessToken (without colon)

I never thought it could be a typo... Anyway, the error was not easy to detect because the redirection to the login form misleaded me from the beginning. I believe it was such an strange behaviour indeed...

like image 148
andcl Avatar answered Oct 02 '22 11:10

andcl