简体   繁体   中英

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' => 'my@email.com',
        '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.

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...

正确的解决方案是从此文件中删除redirectTo()app/http/middleware/Authenticate.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM