使用auth中间件保护某些路由但让其他路由不受保护

时间:2017-06-13 20:40:00

标签: laravel laravel-5.4

我有一个受保护的路线组:

Route::group(['prefix' => 'member', 'middleware' => 'auth'], function () {
    Route::get('/')->name('member.home')->uses('MemberController@index');
    Route::get('show')->name('member.show')->uses('MemberController@show');
    // ...various additional protected member routes...
});

但是,我有两条不受保护的路线:

Route::get('member/pay')->name('member.pay')->uses('MemberController@pay');
Route::get('member/confirm/{payment}')->name('member.confirm')->uses('MemberController@confirm');

只要'middleware' => 'auth'应用于该单独的路由组,即使我不将它们放在组中,所有member前缀路由都会被它覆盖。

我已尝试移动受保护路由组上方和下方的未受保护路由,但除非我完全删除中间件,否则仍会获得401 unauthorized

这不会影响我的任何其他路线......只会以member为前缀。

如何从auth中排除这两条路线?

3 个答案:

答案 0 :(得分:0)

怎么样

Route::group(['prefix' => 'member'], function () {
    Route::get('/')->name('member.home')->uses('MemberController@index')->middleware('auth');
    Route::get('show')->name('member.show')->uses('MemberController@show')->middleware('auth');
    //
    Route::get('member/pay')->name('member.pay')->uses('MemberController@pay');
    Route::get('member/confirm/{payment}')->name('member.confirm')->uses('MemberController@confirm');
});

答案 1 :(得分:0)

一种方法是从Route组中删除中间件分配,而是在MemberController构造函数中分配中间件。这样你可以排除哪些方法不应该应用,如下所示:

class MemberController extends Controller
{
    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth')->except(['pay', 'confirm']);
    }
}

答案 2 :(得分:0)

使用这样的嵌套组。

Route::group([ 'prefix' => 'member' ], function() {
    // Protected routes
    Route::group([ 'middleware' => 'auth' ], function() {
        Route::get('/', 'MemberController@index')->name('member.home');
        Route::get('show', 'MemberController@show')->name('member.show');
        // ...various additional protected member routes...
    });

    // Non protected routes
    Route::get('pay', 'MemberController@pay')->name('member.pay');
    Route::get('confirm/{payment}', 'MemberController@confirm')->name('member.confirm');
    // ...various additional non protected member routes...
});