简体   繁体   English

Laravel 5.4 401 /使用Passport和多种令牌类型进行未经身份验证

[英]Laravel 5.4 401/Unauthenticated using Passport and multiple token types

The backstory on this, I have been working on the instructions from the documentation: https://laravel.com/docs/5.4/passport 关于这个的背景故事,我一直在处理文档中的说明: https//laravel.com/docs/5.4/passport

I have 我有

  1. Laravel 5.4 Laravel 5.4
  2. "laravel/passport": "^3.0" from composer “laravel / passport”:作曲家的“^ 3.0”
  3. Local Mac osx running Mamp pro, Php 7.0.15 本地Mac osx运行Mamp pro,Php 7.0.15

I am calling the sample user route in routes/api.php 我在routes / api.php中调用示例用户路由

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

Postman curl Header (pulled from the code export in Postman): Postman curl Header(从Postman的代码导出中拉出):

CURLOPT_HTTPHEADER => array(
    "accept: application/json",
    "authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImM3ZmI2ZmNmMWFkOGQ0NjFkNTdhMWU2NjFiYjhhOThmOTJhOTBkMDFkNDkwZDFjNDRkNDg5MTdlYjJiZWYyMDlkNjNmOTQwMjIxNTljZWI5In0.eyJhdWQiOiIxIiwianRpIjoiYzdmYjZmY2YxYWQ4ZDQ2MWQ1N2ExZTY2MWJiOGE5OGY5MmE5MGQwMWQ0OTBkMWM0NGQ0ODkxN2ViMmJlZjIwOWQ2M2Y5NDAyMjE1OWNlYjkiLCJpYXQiOjE1MDE3OTQ2NjIsIm5iZiI6MTUwMTc5NDY2MiwiZXhwIjoxNTMzMzMwNjYyLCJzdWIiOiIxIiwic2NvcGVzIjpbImFwaS1hY2Nlc3MiXX0.CPGM4PIKJBeiJvokuDzShz_1CnqHlnFIML-tWoBCn5GcijMXmQkWOHzTI8QwTws2h719TGA4hemXDljjqoZB0LiztAx2JZ3OhjNS-MhrMNujnTJUbvkXAVfcRdybhlDEWof_iboLICQTYNTslX1iw-2DCyFMh8gB4INAKUhpvzA955ALB-ZunKrjSNKdRkgtZRe0t6VyJf9LwzgjIAfSKoi_qRis36KD7hcf0Id_iWZkhvS-ZfuM5eUpzUooUe0rb4rkYYEYndlHlY7-uuZPlzmPMpaJTR4AW1CLkaK5Ic7fde1x1kk2duW_Znd9ki2YBP0kw7ifAmg2DaM5r2-0kEx_1iFuCIxE8QJns1aIm3XjWoOApovt7V6-s3yJZK3xlIDCjFI-C59RHiVSabh-hKdX4elvSL9taSQyuramPZPpsne9SUh4KCWul0iHoNjFdFJEut_TUBWyUPtD3J7gg6P97uRS_THDAUHMo2UYVhlnu9PV8SvbvjGj3OeaaH7ZbzWQCYKbqsLZAZ2mnJlFhTMghbaC2s_MND1zlRm7w9btmihxVW714NUbH8UAwSvrtIYYQ0itevZ59TLiAXprjmjkhiFkrhdX4bUje4uNEbLYawkZI-1o82IExW9D8kCYpOWOZdWTCLgmaE2wXcf-DTCV-9vDWRAdX1YmP4JbRsc",
    "cache-control: no-cache",
    "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
    "postman-token: 2ec7a2c8-3489-812d-4638-ebb7dc62aeb1"
  ),

I have 1 personal access token generated using the Vue Components 我有一个使用Vue组件生成的个人访问令牌

I have checked that i am setting the token expiration for 1 year and that is reflecting in the db. 我已经检查过我将令牌过期设置为1年,这反映在数据库中。

My AuthServiceProvider.php 我的AuthServiceProvider.php

Passport::routes();

        // TODO MAKE THEM LAST A LONG TIME
        Passport::tokensExpireIn(Carbon::now()->addYears(20));//You can also use addDays(10)
        Passport::refreshTokensExpireIn(Carbon::now()->addYears(20));//You can also use addDays(10) 
        Passport::pruneRevokedTokens(); //basic garbage collector

        Passport::tokensCan([
            'api-access' => 'Access Complete API',
        ]);

My RouteServiceProvider.php (mapApiRoutes is called in the map function) 我的RouteServiceProvider.php(mapApiRoutes在map函数中调用)

protected function mapApiRoutes()
    {
        Route::group([
            'namespace' => $this->namespace,
            'prefix' => 'api',
        ], function ($router) {
            require base_path('routes/api.php');
        });
    }

My Kernel.php route middleware 我的Kernel.php路由中间件

protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

-- EDIT -- AFTER MORE RESEARCH - 编辑 - 更多研究之后

I am using postman to test out my api auth and get a 401 each time I try. 我正在使用邮递员来测试我的api auth并且每次尝试都会获得401。 I have tried Personal Access Client and Password Grant Client and both have the same issue. 我尝试过个人访问客户端和密码授予客户端,两者都有相同的问题。 After looking at them both I realized that both use Authorization Bearer [token] format. 看着它们后,我意识到两者都使用授权承载[令牌]格式。

So I started Logging out in various files in Passport source. 所以我开始在Passport源中的各种文件中注销。

In the TokenGuard.php 在TokenGuard.php中

public function user(Request $request) {

    Log::info('TokenGuard: '. $request);

    if ($request->bearerToken()) {
        return $this->authenticateViaBearerToken($request);
    } elseif ($request->cookie(Passport::cookie())) {
        return $this->authenticateViaCookie($request);
    }
}

The Log looks like this: 日志看起来像这样:

[2017-08-10 20:50:20] local.INFO: TokenGuard 93: GET /api/user HTTP/1.1
Accept:          application/json
Accept-Encoding: gzip, deflate
Cache-Control:   no-cache
Connection:      keep-alive
Content-Type:    application/json
Host:            url.com:8888
Postman-Token:   66707fe5-8f6e-4920-948b-2804a76d4a65
User-Agent:      PostmanRuntime/6.2.5


[2017-08-10 20:50:20] local.INFO: TokenGuard 93: GET /api/user HTTP/1.1
Accept:          application/json
Accept-Encoding: gzip, deflate
Cache-Control:   no-cache
Connection:      keep-alive
Content-Type:    application/json
Host:            url.com:8888
Postman-Token:   66707fe5-8f6e-4920-948b-2804a76d4a65
User-Agent:      PostmanRuntime/6.2.5

The thing missing is the Bearer [token] portion of the request. 缺少的是请求的Bearer [token]部分。 The TokenGuard code chunk is running an if/else. TokenGuard代码块正在运行if / else。 This is where I think the failure is happening. 这就是我认为失败的地方。

Shouldn't it be logging that out too? 难道不应该记录下来吗? Since the Bearer Token is missing the If/Else fails and then it makes sense to return a 401. 由于Bearer Token缺失,If / Else失败,然后返回401是有意义的。

Why would my Token be stripped out of the request. 为什么我的令牌会被删除。

Add this to your .htaccess file under public directory of your project: 将其添加到项目公共目录下的.htaccess文件中:

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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