Laravel Passport未处理网站自己的API调用

时间:2018-05-07 07:04:53

标签: php laravel laravel-passport

我正在使用Laravel 5.4AngularJS。我创建的APIs由我自己的网站AngularJS Ajax方法,Mobile App以及某些Third-party apps调用。

对于API authentication我正在使用Laravel Passport ~4.0Password Grant。每次通过API电话都可以正常运行,但我无法authenticate API使用我的网站Ajax来电。

根据Laravel Passport Documentation,如果我在\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class中间件组中使用提供商web,那么我不需要为我自己设置Authorization Header { {1}}来电,API会为我处理。 (请参阅提供的链接中的#Consuming Your API with JavaScript Para:2)

请查看下面的代码实现:

配置/ app.php:

Laravel

应用/模型/ user.php的:

<?php
    return [
        'providers' => [
            Laravel\Passport\PassportServiceProvider::class
        ]
    ];

app / Providers / AuthServiceProvider.php:

<?php
    namespace App\Models;
    use Laravel\Passport\HasApiTokens;
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Database\Eloquent\SoftDeletes;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use App\Traits\Encryptable;

    class User extends Authenticatable
    {
        use HasApiTokens;
        use SoftDeletes;
        use Notifiable;
        use Encryptable;

        protected $table = 'users';
    }

配置/ auth.php:

<?php
    namespace App\Providers;
    use Laravel\Passport\Passport;
    use Illuminate\Support\Facades\Gate;
    use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

    class AuthServiceProvider extends ServiceProvider{

        protected $policies = [
            'App\Model' => 'App\Policies\ModelPolicy',
        ];

        public function boot(){
            $this->registerPolicies();
            Passport::routes();
        }
    }

路由/ api.php

<?php
    return [
        'guards' => [
            'web' => [
                'driver' => 'session',
                'provider' => 'users',
            ],
            'api' => [
                'driver' => 'passport',
                'provider' => 'users',
            ],
        ],
    ];

routes / web.php:

<?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: Authorization, Content-Type, mobile-app' );
    header('Access-Control-Allow-Methods', '*');
    use Illuminate\Http\Request;

    Route::group(['prefix' => '/v1','middleware'=>['auth:api']], function () {
        //Some APIs are here which returns JSON
    });

应用/ HTTP / Kernel.php

<?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: Authorization, Content-Type, mobile-app' );
    header('Access-Control-Allow-Methods', '*');

    Route::get('/',function(){
        if(\Auth::check()){
            return redirect('/dashboard');
        }
        return redirect('/login');
    });

    Route::group(['middleware' => array('auth')], function(){
        //Some web routes here which returns html views
    }); 

我正在使用<?php protected $middlewareGroups = [ 'web' => \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class, ], ]; 执行的Ajax请求如下:

AngularJS

请求function makeRequest(url, params, method) { var requestUrl = '/' + url; if(params != null){ var requestUrl = '/' + url+'?page=1'; } angular.forEach(params, function(value, key){ requestUrl = requestUrl + '&' + key + '=' + value; }); return $http({ 'url': requestUrl, 'method': method, 'headers': { 'accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }, 'cache': false }).then(function(response){ return response.data; }).catch(dataServiceError); } 页面返回html /dashboardviewRequest为:

Response

使用General: Request URL: http://local.something.com/dashboard Request Method: GET Status Code: 200 OK Remote Address: 127.0.0.1:80 Referrer Policy: no-referrer-when-downgrade Request Headers: Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9,gu;q=0.8 Cache-Control: max-age=0 Connection: keep-alive Cookie: laravel_token=eyJpdiI6IjBxXC9zVUhmKzdZMDZqVVwvM0s2V1Y0QT09IiwidmFsdWUiOiJhMmNmOTBtTEZmZE16N0pDRmVDWURlZURVaHlhSUVaZ003TldrbjhmRmdFWmU2SENMTDVLbHdRMmNRK1dDazBGZnkwaER4QVR4b2doQzliWXVQSzBldU1hMWM0UTVycCtVOU9uMzlNa2IyR3gzektXS1FiQTJXd1dcL2xXeFpNZzNRZWJEVjdDRFZleklheVJsU0FSY1dlZEZQWm1lV3hHV0hHN3JwMSs4MncwTkhjN0RNd1hXVENrcGZFR29tMHZXdGxicks3a1J2TjRhNUlNalhiTG5oem1DVHpZWlRvaHIxQzZrY3pqNytNMEhxSkJwUkMxY0NsZmFBY2s5T0VDYzJGUW5MdEZqYm5Kc09vcDdLU1hWdkE9PSIsIm1hYyI6ImY5YzEyNTMxYzYxMTYyZjQ2OWJkZWU1NTkyYjkzYjQzM2Q4Y2NjMzkyMzk3ZDMzNTllNzQ5NGJmYzI4YmFhZDYifQ%3D%3D; XSRF-TOKEN=eyJpdiI6IlpOcllLTDRkYmsrbmRhTnF6NFQ0Z0E9PSIsInZhbHVlIjoiY2VES3d2VGhIcUlnczdOQmV4VzVISHpnUXRFS1lra2dHTXN5VmR0bEQweEVjejlFTFpRczNEdTNtSGRUdW1TS2IyTU01QVwvZCt2RVVmOHRHUUYrRzlBPT0iLCJtYWMiOiI5ZTZhMjE3ZGE2MTliNmNkMzg4ZTg5ODA0MTEyN2E4YTZhNTgxMWFhYWIwMTFhNTM5YWYzMjViMzMxOTkyNjU2In0%3D; laravel_session=eyJpdiI6IktlNUpPd0s2djRzQXlVakRuUkxUR3c9PSIsInZhbHVlIjoicVwvSmlLaVpWK2hKSytQcUU5WmJCdmJIR2ZPS2JnT1FKbWY2M0VLOVNzYlBcL3pJYnl6c1RrVWFVQVlHWUNodjgzdk92WStRVDl1cHEzUGtPRStMUmhPZz09IiwibWFjIjoiODg4YzhmYjQ0NzE2ZDI2MWY1YmU2MmJiYjUxZjk0NTA5MmNiY2ZkZDEwYjk0OTFjZTY0MTE5ODk0MjZmYjRkMSJ9 Host: local.something.com Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36 Response Headers: Access-Control-Allow-Headers: Authorization, Content-Type, mobile-app Access-Control-Allow-Origin: * Cache-Control: no-cache, private Connection: Keep-Alive Content-Type: text/html; charset=UTF-8 Date: Mon, 07 May 2018 06:21:59 GMT Keep-Alive: timeout=5, max=100 Server: Apache/2.4.23 (Win64) PHP/7.2.4 Set-Cookie: XSRF-TOKEN=eyJpdiI6IjVWbGlOekVib1QycWFHMTlVb01ENnc9PSIsInZhbHVlIjoibjQzNXFkME95MmMzekJ4cUNOSldpQXY4dE95YVlxV3dsMFNZc1hGZHQySk9lSE5MTXRiS1FJSVNiXC9cL0V4VEFQb1V0Qnl1V1FFb0RhM0Roa2xCVk9zZz09IiwibWFjIjoiMjJmZGRlNzU0MDBmNzA1MzdhYTRmMWNkMjM5YjBmYjU2YzMwOWM1OGFkNmMwYzQ3YTIwMTYzYzY1M2M5ZGZiMiJ9; expires=Mon, 07-May-2018 08:22:00 GMT; Max-Age=7200; path=/ Set-Cookie: laravel_session=eyJpdiI6InVPWUplcE1GZnVHNUYxXC9YMWl1UmtnPT0iLCJ2YWx1ZSI6IlQxUkpmVllhb0R2dkpiZDFWd0xlWXg5WGxjQTY5dFY2R3BjdGNvTVhoc1pORnE5b0ttMXhcL2NZbFErOVwvMnUwTDAwcFFLXC9ySzdaMkxSR1wva3NEMW1mUT09IiwibWFjIjoiNGYxYmM2NmNhMjE1NjliNGYzYmFiYTdhZmY2ZWY5NzM1MmI5ZjQ3ZTdlY2JjMDg5ODkxMWQwOTBiNjM2MDQzZSJ9; expires=Mon, 07-May-2018 08:22:00 GMT; Max-Age=7200; path=/; HttpOnly Set-Cookie: laravel_token=eyJpdiI6ImYxdDB4SGpnWGptMnBNM3lWc2pvY0E9PSIsInZhbHVlIjoiRDZheEtEeHdPT2EyQWFuZ1NPOHcwSnRtUnZ3aW1jOVhxNGtBRnZQK01OakZaTmNIQ1JVMkJ4MGl3RjdhR0NzR0VVODlaWDNyTXVWOXpjS1lOOWNEeDh0OGxISnBWUnU4V0NwKzdheVN0bGJkSVk2dGNnYng3c1p1OGExVGFKejR1M2JjMGlSVzJ3WElEbEFlVTNUeVA1ODdTZXE5alBqWSs5aXV5UUlZVkRmSGppTm0zSnNZc2tEMEhzTEt2NEZ6K0t4eDI0WDdDUmJGYm44NGc4aXo4akxMRVFySmdZblwvMEtMZDJYVTFYU0pBVDY5RG9SdmhlaDF0REhONEpLNHNJbWppZWxrS1Nhd0ZjU2ZVazJqdCtBPT0iLCJtYWMiOiJkMmE1NTc4YTFhYTRlODFmOWY5YjllNmM1MDA4Nzg4ODg5Njg2NDI1Zjk3MzdkYmFlNzg2YzNkZjI3NzYzOWY0In0%3D; expires=Mon, 07-May-2018 08:22:00 GMT; Max-Age=7200; path=/; HttpOnly Transfer-Encoding: chunked X-Powered-By: PHP/7.2.4 获取用户数据的API请求如下:

Ajax

这会返回General: Request URL: http://local.something.com/api/v1/user/3/data Request Method: GET Status Code: 401 Unauthorized Remote Address: 127.0.0.1:80 Referrer Policy: no-referrer-when-downgrade Request Headers: accept: application/json Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9,gu;q=0.8 Connection: keep-alive Cookie: laravel_token=eyJpdiI6ImYxdDB4SGpnWGptMnBNM3lWc2pvY0E9PSIsInZhbHVlIjoiRDZheEtEeHdPT2EyQWFuZ1NPOHcwSnRtUnZ3aW1jOVhxNGtBRnZQK01OakZaTmNIQ1JVMkJ4MGl3RjdhR0NzR0VVODlaWDNyTXVWOXpjS1lOOWNEeDh0OGxISnBWUnU4V0NwKzdheVN0bGJkSVk2dGNnYng3c1p1OGExVGFKejR1M2JjMGlSVzJ3WElEbEFlVTNUeVA1ODdTZXE5alBqWSs5aXV5UUlZVkRmSGppTm0zSnNZc2tEMEhzTEt2NEZ6K0t4eDI0WDdDUmJGYm44NGc4aXo4akxMRVFySmdZblwvMEtMZDJYVTFYU0pBVDY5RG9SdmhlaDF0REhONEpLNHNJbWppZWxrS1Nhd0ZjU2ZVazJqdCtBPT0iLCJtYWMiOiJkMmE1NTc4YTFhYTRlODFmOWY5YjllNmM1MDA4Nzg4ODg5Njg2NDI1Zjk3MzdkYmFlNzg2YzNkZjI3NzYzOWY0In0%3D; XSRF-TOKEN=eyJpdiI6IjVWbGlOekVib1QycWFHMTlVb01ENnc9PSIsInZhbHVlIjoibjQzNXFkME95MmMzekJ4cUNOSldpQXY4dE95YVlxV3dsMFNZc1hGZHQySk9lSE5MTXRiS1FJSVNiXC9cL0V4VEFQb1V0Qnl1V1FFb0RhM0Roa2xCVk9zZz09IiwibWFjIjoiMjJmZGRlNzU0MDBmNzA1MzdhYTRmMWNkMjM5YjBmYjU2YzMwOWM1OGFkNmMwYzQ3YTIwMTYzYzY1M2M5ZGZiMiJ9; laravel_session=eyJpdiI6InVPWUplcE1GZnVHNUYxXC9YMWl1UmtnPT0iLCJ2YWx1ZSI6IlQxUkpmVllhb0R2dkpiZDFWd0xlWXg5WGxjQTY5dFY2R3BjdGNvTVhoc1pORnE5b0ttMXhcL2NZbFErOVwvMnUwTDAwcFFLXC9ySzdaMkxSR1wva3NEMW1mUT09IiwibWFjIjoiNGYxYmM2NmNhMjE1NjliNGYzYmFiYTdhZmY2ZWY5NzM1MmI5ZjQ3ZTdlY2JjMDg5ODkxMWQwOTBiNjM2MDQzZSJ9 Host: local.something.com Referer: http://local.something.com/dashboard User-Agent: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36 X-Requested-With: XMLHttpRequest X-XSRF-TOKEN: eyJpdiI6IjVWbGlOekVib1QycWFHMTlVb01ENnc9PSIsInZhbHVlIjoibjQzNXFkME95MmMzekJ4cUNOSldpQXY4dE95YVlxV3dsMFNZc1hGZHQySk9lSE5MTXRiS1FJSVNiXC9cL0V4VEFQb1V0Qnl1V1FFb0RhM0Roa2xCVk9zZz09IiwibWFjIjoiMjJmZGRlNzU0MDBmNzA1MzdhYTRmMWNkMjM5YjBmYjU2YzMwOWM1OGFkNmMwYzQ3YTIwMTYzYzY1M2M5ZGZiMiJ9 Response Headers: Access-Control-Allow-Headers: Authorization, Content-Type, mobile-app Access-Control-Allow-Origin: * Cache-Control: no-cache, private Connection: Keep-Alive Content-Length: 12 Content-Type: text/html; charset=UTF-8 Date: Mon, 07 May 2018 06:22:00 GMT Keep-Alive: timeout=5, max=100 Server: Apache/2.4.23 (Win64) PHP/7.2.4 Set-Cookie: laravel_session=eyJpdiI6Im82TGNRVms0aUtSNHNVbzdKZXZYb0E9PSIsInZhbHVlIjoiY1wvTmZXV3o0SVYyRmVoMzRheWNaRHBDV29jWmI2S3JvQjNBOEVjNHlsQkpKMWlRMWdYWlU1ckdnbTRIOVllSmZIOVpud01BTExtSURXNHdDdkZZMDNnPT0iLCJtYWMiOiIyMzc4YjczNTFmYmJlNDg3N2UxZDJlODg0NDFjNjEyZjhhYWM4YTk4MTMzZDk0NjUyY2ZkNjY0MTUzZWZjYjVlIn0%3D; expires=Mon, 07-May-2018 08:22:01 GMT; Max-Age=7200; path=/; HttpOnly X-Powered-By: PHP/7.2.4 X-RateLimit-Limit: 300 X-RateLimit-Remaining: 299 未经授权,我不知道为什么?问题出在401次调用,我的API仅使用own web-application。对于移动应用和第三方应用,我们使用Ajax标头,一切似乎都正常。任何人都可以让我知道我错过了什么或如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

经过大量追踪后,我发现app/Http/Kernel.php存在问题。 在protected $middlewareGroups中,middlewares部分中添加了一些api,如:

protected $middlewareGroups = [ 'api' => [ 'throttle:300,1', \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, 'bindings', ], ];

这些正在加密cookie,因此它返回401 Unauthorised。我删除了它们:

protected $middlewareGroups = [ 'api' => [ 'throttle:300,1', 'bindings', ], ];

并且代码开始工作。