middleware.dev redirected you too many times

拥有回忆 提交于 2020-01-06 05:24:11

问题


I am running laravel version 5.4.26

my localhost project url is : middleware.dev. first time login in this url :

middleware.dev/login

,and login successfully completed. Then enter this url :

middleware.dev/admin

,then error message bellow

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;
    }
}

回答1:


This problem is most probably due to a loop in your redirection like you redirect to a route which redirects you back to the same route forming a loop.

The problem seems to be with your logic in IsAdmin middleware. The logic reads If the user is admin then redirect to /admin otherwise pass the request where it is headed which is again /admin route.

This is where the problem is. For instance, you hit middleware.dev/admin it will cross through IsAdminmiddleware and on confirming that user is admin will again redirect it to /adminroute which creates a loop.




回答2:


Try this in IsAdmin middleware

<?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);



    }
}



回答3:


Try this inside IsAdmin.php Class:

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

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

    return $next($request);
}


来源:https://stackoverflow.com/questions/44635635/middleware-dev-redirected-you-too-many-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!