middleware.dev 重定向您的次数过多

middleware.dev redirected you too many times

我是运行laravel版本5.4.26

我的本地主机项目 url 是:middleware.dev。第一次登录 url :

中间件.dev/login

,登录成功。然后输入这个 url :

中间件.dev/admin

,然后是下面的错误消息

This page isn’t working

middleware.dev redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS

Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

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,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::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\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

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

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    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,
        'role'=>\App\Http\Middleware\RoleMiddleware::class,
        'IsAdmin'=>\App\Http\Middleware\IsAdmin::class,


    ];
}

IsAdmin.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $user =Auth::user();

        if ($user->isAdmin()){

            return redirect()->intended('/admin');
        }

                return $next($request);



    }
}

web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

use Illuminate\Support\Facades\Auth;

Route::get('/', function () {

    return view('welcome');




});









Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/admin/user/roles',['middleware'=>['role','auth','web'],function (){

    return 'Middleware role';
}]);

Route::get('/admin', 'AdminController@index');

AdminController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AdminController extends Controller
{
    //


    public function __construct()
    {
        $this->middleware('IsAdmin');
    }

    public function index(){

        return 'you are administretor becuse you ar sign in the page';
    }

}

User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function role(){
        return $this->belongsTo('App\Role');
    }

    public function isAdmin(){

        if ($this->role['name'] =='administrator'){

            return true;
        }

        return false;
    }
}

这个问题很可能是由于重定向中的循环造成的,例如您重定向到一条路由,该路由又将您重定向回同一路由,从而形成循环。

问题似乎与您在 IsAdmin 中间件中的逻辑有关。逻辑如下:如果用户是管理员,则重定向到 /admin 否则将请求传递到它要去的地方,这又是 /admin 路由。

这就是问题所在。例如,您点击 middleware.dev/admin 它将穿过 IsAdmin 中间件,并且在确认用户是管理员时将再次将其重定向到 /admin 创建循环的路由。

在里面试试这个 IsAdmin.php Class:

public function handle($request, Closure $next)
{
    $user = Auth::user();

    if(!$user->isAdmin()){
        return redirect('/');
    }

    return $next($request);
}

在 IsAdmin 中间件中试试这个

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Route;

class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $user =Auth::user();

        if ($user->isAdmin() && Route::currentRouteAction() != 'App\Http\Controllers\AdminController@index' ){

            return redirect()->intended('/admin');
        }

                return $next($request);



    }
}