【问题标题】:Laravel 5.2: session and token guard on the same routesLaravel 5.2:相同路由上的会话和令牌保护
【发布时间】:2017-01-31 05:18:54
【问题描述】:

我们有会话守卫,这就足够了。

现在我们需要通过令牌(在标头或 GET 参数中)和通过会话在相同的路由上添加授权。

通过令牌授权必须是无状态的。

更新: 首先,我们考虑创建重复的路线。 一个用于会话,一个用于令牌

// api token auth
// url: /api/test
Route::group(['middleware' => ['web', 'auth:api'], 'prefix' => 'api', 'as' => 'api.'], function () {
    Route::resource('test', 'TestController');
    // 50+ routes
});

// session auth
// url: /test
Route::group(['middleware' => ['web', 'auth']], function () {
    Route::resource('test', 'TestController');
    // 50+ routes
});

但这不是我们想要的,因为 url 不同。

也许有人知道如何解决这个问题?

【问题讨论】:

    标签: php api laravel laravel-5.2 authorization


    【解决方案1】:

    创建新的中间件 AuthenticateWithToken:

    class AuthenticateWithToken
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @param  string|null  $guard
         *
         * @return mixed
         */
        public function handle($request, Closure $next, $guard = null)
        {
            if (($user = Auth::guard('api')->user())) {
                Auth::setUser($user);
            }
    
            return $next($request);
        }
    }
    

    在Http/Kernel.php中声明:

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        // ...
        'auth.api' => \App\Http\Middleware\AuthenticateWithToken::class,
        // ...
    ];
    

    并将其添加到 routes.php 中默认的 'auth' 中间件之前:

    Route::group(['middleware' => ['web', 'auth.api', 'auth']], function () {
        Route::resource('test', 'TestController');
        // 50+ routes
    });
    

    【讨论】:

    • 知道如何做同样的事情,但使用护照而不是令牌保护?
    • 没关系只需要使用 'auth.api' 中间件而没有任何其他
    猜你喜欢
    • 2021-05-03
    • 2015-03-11
    • 2021-11-04
    • 1970-01-01
    • 2016-05-23
    • 2017-05-10
    • 2022-11-16
    • 1970-01-01
    • 2021-01-05
    相关资源
    最近更新 更多