Laravel中间件“除了”规则不起作用

时间:2016-01-10 21:45:06

标签: laravel laravel-5 laravel-middleware

我在构造函数中有一个带有以下内容的控制器:

$this->middleware('guest', ['except' =>
    [
        'logout',
        'auth/facebook',
        'auth/facebook/callback',
        'auth/facebook/unlink'
    ]
]);

“注销”规则(默认情况下存在)可以很好地工作,但我添加的其他3个规则将被忽略。 routes.php中的路线如下所示:

Route::group(['middleware' => ['web']],function(){

    Route::auth();

    // Facebook auth
    Route::get('/auth/facebook', 'Auth\AuthController@redirectToFacebook')->name('facebook_auth');
    Route::get('/auth/facebook/callback', 'Auth\AuthController@handleFacebookCallback')->name('facebook_callback');
    Route::get('/auth/facebook/unlink', 'Auth\AuthController@handleFacebookUnlink')->name('facebook_unlink');
}

如果我在登录时访问auth/facebookauth/facebook/callbackauth/facebook/unlink,我会被中间件拒绝并退回主页。

我已尝试通过继续/来指定“除外”规则,因此它们与routes.php中的路由完全匹配,但没有区别。有什么想法被忽略这些规则,而默认的“注销”规则是否得到尊重?

干杯!

7 个答案:

答案 0 :(得分:15)

您应该通知方法名称而不是URI。

01-11 22:06:54.649 I/BGService(10078): tick1
01-11 22:07:50.664 I/BGService(10078): tick2

答案 1 :(得分:2)

我通过添加此inExceptArray函数在中间件中解决了此问题。 VerifyCsrfToken处理除外数组的方式相同。

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class MyMiddleware
{
    /**
     * Routes that should skip handle.
     *
     * @var array
     */
    protected $except = [
        '/some/route',
    ];

    /**
     * Determine if the request has a URI that should pass through.
     *
     * @param Request $request
     * @return bool
     */
    protected function inExceptArray($request)
    {
        foreach ($this->except as $except) {
            if ($except !== '/') {
                $except = trim($except, '/');
            }

            if ($request->is($except)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // check user authed or API Key
        if (!$this->inExceptArray($request)) {
            // Process middleware checks and return if failed...
            if (true) {
              // Middleware failed, send back response
              return response()->json([
                'error' => true,
                'Message' => 'Failed Middleware check'
            ]); 
            }
        }
        // Middleware passed or in Except array
        return $next($request);
    }
}

答案 2 :(得分:0)

如果您正在尝试遵循Laravel文档,则可以通过在/Http/Middleware/VerifyCsrfToken.php文件中向$ except变量添加路由来建议替代解决方案。文档说要像这样添加它们:

'route/*'

但我发现让它发挥作用的唯一方法就是将路由放在这样忽略:

'/route'

答案 3 :(得分:0)

我已经解决了这个问题,这就是我正在做的事情。麻生太郎,我刚刚意识到这与 cmac 在他的回答中所做的非常相似。

api.php

Route::group(['middleware' => 'auth'], function () {
    Route::get('/user', 'Auth\UserController@me')->name('me');
    Route::post('logout', 'Auth\LoginController@logout')->name('logout');
});

LoginController.php

class LoginController extends Controller
{
    use AuthenticatesUsers, ThrottlesLogins;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    // ...

    /**
     * If the user's session is expired, the auth token is already invalidated,
     * so we just return success to the client.
     *
     * This solves the edge case where the user clicks the Logout button as their first
     * interaction in a stale session, and allows a clean redirect to the login page.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $user = $this->guard()->user();

        if ($user) {
            $this->guard()->logout();
            JWTAuth::invalidate();
        }

        return response()->json(['success' => 'Logged out.'], 200);
    }
}

Authenticate.php

class Authenticate extends Middleware
{
    /**
     * Exclude these routes from authentication check.
     *
     * Note: `$request->is('api/fragment*')` https://laravel.com/docs/7.x/requests
     *
     * @var array
     */
    protected $except = [
        'api/logout',
    ];

    /**
     * Ensure the user is authenticated.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            foreach ($this->except as $excluded_route) {
                if ($request->path() === $excluded_route) {
                    \Log::debug("Skipping $excluded_route from auth check...");
                    return  $next($request);
                }
            }

            // code below here requires 'auth'

        { catch ($e) {
            // ...
        }

    }

我对其进行了稍微的过度设计。今天,我只需要对/api/logout进行豁免,但是我设置了逻辑以快速添加更多路由。如果您研究VerifyCsrfToken中间件,您会发现它采用这样的形式:

    protected $except = [
        'api/logout',
        'api/foobars*',
        'stripe/poop',
        'https://www.external.com/yolo',
    ];

这就是为什么我在上面的文档中放置“注释”的原因。 $request->path() === $excluded_route可能与api/foobars*不匹配,但$request->is('api/foobars*')应该匹配。另外,一个人也许可以使用类似$request->url() === $excluded_route之类的东西来匹配http://www.external.com/yolo

答案 4 :(得分:0)

将中间件分配给一组路由时,有时可能需要防止将中间件应用于该组中的单个路由。您可以使用noMiddleware方法完成此操作:

use App\Http\Middleware\CheckAge;

Route::middleware([CheckAge::class])->group(function () {
    Route::get('/', function () {
        //
    });

    Route::get('admin/profile', function () {
        //
    })->withoutMiddleware([CheckAge::class]);
});

有关更多信息,请阅读documentation laravel middleware

答案 5 :(得分:0)

在您的控制器中使用此功能:

public function __construct()
    {
        $this->middleware(['auth' => 'verified'])->except("page_name_1", "page_name_2", "page_name_3");
    }

*用您的替换page_name_1 / 2/3。

对我来说一切正常。

答案 6 :(得分:0)

您应该将函数名称传递给 'except'。

以下是我的一个项目的示例:

$this->middleware('IsAdminOrSupport', ['except' => [
        'ProductsByShopPage'
        ]
    ]);

这意味着中间件“IsAdminOrSupport”应用于此控制器的所有方法,但方法“ProductByShopPage”除外。