在laravel 5.2中禁用特定路由的Web中间件

时间:2016-02-13 06:52:05

标签: php laravel authentication middleware laravel-5.2

我希望访客用户可以访问主页但是在内置身份验证过程中laravel重定向到登录页面。如何让访客用户访问主页?

我的routes.php:

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

Route::get('/', 'HomeController@index');

Route::get('/insert', 'HomeController@insertform');
Route::get('/job/{id}', 'JobsController@show');

Route::get('/city/{city}', 'JobsController@city');

Route::post('/insert', 'HomeController@insert');
Route::get('/cityinsert', 'HomeController@cityinsert');
Route::post('/cityinsert', 'HomeController@cityinsertpost');

});

和authenticate.php

class Authenticate
{
 /**
 * 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 (Auth::guard($guard)->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login');
        }
    }

    return $next($request);
}
}

这是我的kernel.php

class Kernel extends HttpKernel
{
/**
 * The application's global HTTP middleware stack.
 *
 * These middleware are run during every request to your application.
 *
 * @var array
 */
protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
    ],
];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}

6 个答案:

答案 0 :(得分:15)

在构造

中的中间件声明中添加异常
Route::get('/', 'HomeController@index');

要使上述路由免于身份验证,您应该将函数名称传递给中间件,如下所示

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

答案 1 :(得分:8)

我更喜欢通过路由排除中间件。您可以通过两种方式做到这一点:

  1. 单个动作:
Route::post('login', 'LoginController@login')->withoutMiddleware(['auth']);
  1. 分组模式:
Route::group([
    'prefix' => 'forgot-password',
    'excluded_middleware' => ['auth'],
], function () {
    Route::post('send-email', 'ForgotPasswordController@sendEmail');
    Route::post('save-new-password', 'ForgotPasswordController@saveNewPassword');
});

在Laravel 7.7上测试

答案 2 :(得分:7)

从HomeController结构中删除中间件:

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('auth');
    }
}

答案 3 :(得分:2)

我可以添加到Sidharth的答案,你可以使用几个方法exeption,将它们包含在数组中:

$config = [
    'components' => 
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'localhost', // '127.0.0.1'
                'port' => '25',
            ]
        ],
    ],
];

Laravel 5.5测试过。

答案 4 :(得分:0)

您还可以在middlewareexcept之间进行分隔。试试这个:

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

在Laravel 5.4上测试

答案 5 :(得分:0)

将URL以外的内容添加到VerifyCsrfToken

app/http/middleware/VerifyCsrfToken.php
<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

来源:Laravel Documentation CSRF exclude URL

*也在Lavarel 7.0上进行了测试