简体   繁体   English

ERR_TOO_MANY_REDIRECTS laravel管理/登录页面

[英]ERR_TOO_MANY_REDIRECTS laravel admin/login page

I have a three logins with three different view and routes. 我有三个具有三个不同视图和路线的登录名。 whenever i hit a localhost:8080/admin/login its shows error ERR_TOO_MANY_REDIRECTS. 每当我按下localhost:8080 / admin / login时,它就会显示错误ERR_TOO_MANY_REDIRECTS。 when i hit admin/ for dashboard its successfully redirects me to admin/login. 当我点击admin /的仪表板时,它成功地将我重定向到admin / login。

In AdminController when i replace $this->middleware('auth:admin'); 当我替换$ this-> middleware('auth:admin')时,在AdminController中; with $this->middleware('guest:admin'); 使用$ this-> middleware('guest:admin'); in __constructor function, redirects problem gets solved but when i go to admin/home it does't redirect to admin/login. 在__constructor函数中,重定向问题得到解决,但是当我转到admin / home时,它不会重定向到admin / login。

I am using latest laravel 5.7.xx and i am not using its inbuild auth view. 我正在使用最新的laravel 5.7.xx,并且没有使用其内置身份验证视图。 Its my customized. 它是我定制的。

config/auth.php code config / auth.php代码

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'admin-api' => [
            'driver' => 'token',
            'provider' => 'admins',
        ],

        'trainer' => [
            'driver' => 'session',
            'provider' => 'trainer',
        ],
        'trainer-api' => [
            'driver' => 'token',
            'provider' => 'trainer',
        ],
    ],

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],
        'trainer' => [
            'driver' => 'eloquent',
            'model' => App\Trainer::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'admins' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'trainer' => [
            'provider' => 'trainer',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

app/Admin.php app / Admin.php

<?php

namespace App;

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

class Admin extends Authenticatable
{
    use Notifiable;

    protected $guard = 'admin';

    /**
     * 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',
    ];
}

Below is my Exceptions/Handler.php code 以下是我的Exceptions / Handler.php代码

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

use Request;
use Illuminate\Auth\AuthenticationException;
use Response;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

    public function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        $guard = array_get($exception->guards(),0);

        switch ($guard) {
            case 'admin':
                $login = 'admin.login';
                break;
            case 'trainer':
                $login = 'trainer.login';
                break;
            case 'user':
                $login = 'user.login';
                break;
            default:
                $login = 'laravel';
                break;
        }

        return redirect()->guest(route($login));
    }
}

Http/Controllers/AdminController.php code Http / Controllers / AdminController.php代码

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
// use Illuminate\Support\Facades\Auth;
use Auth;
use Validator;

class AdminController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    // login
    public function index()
    {
        return view('admin.index');
    }

    // admin login
    public function login(Request $requests)
    {
        // Validate the form data
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required'
        ]);

        // Attempt to log the user in
        if(Auth::guard('admin')->attempt(['email' => $request->email,'password' => $request->password,'usertype' => 1,'status' => 1])){
            // if success
            return redirect()->intended(route('admin.home'));
        }

        // if failed
        return redirect()->back()->withInput($request->only('email'));
    }

    // admin logout
    public function logout()
    {
        Auth::guard('admin')->logout();
        return redirect()->intended(route('admin.login'));
    }

    // base
    public function base()
    {
        return view('admin.base');
    }

    // dashboard
    public function home()
    {
        return view('admin.home');
    }
}

Http/Middleware/RedirectIfAuthenticated.php code Http / Middleware / RedirectIfAuthenticated.php代码

<?php

namespace App\Http\Middleware;

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

class RedirectIfAuthenticated
{
    /**
     * 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)
    {
        switch ($guard) {
            case 'admin':
                if (Auth::guard($guard)->check()) {
                    return redirect(route('admin.home'));
                }
                break;
            case 'trainer':
                if (Auth::guard($guard)->check()) {
                    return redirect(route('trainer.home'));
                }
                break;
            case 'user':
                if (Auth::guard($guard)->check()) {
                    return redirect(route('user.home'));
                }
                break;
            default:
                return redirect(route('laravel'));
                break;
        }

        return $next($request);
    }
}

routes/web.php 路线/web.php

Auth::routes();

/* Admin */
Route::prefix('admin')->group(function(){
    Route::get('/login','AdminController@index')->name('admin.login');
    // Route::post('/login','AdminController@login')->name('admin.login.submit');
    // Route::post('/logout','AdminController@logout')->name('admin.logout');
    Route::get('/base','AdminController@base')->name('admin.base');
    Route::get('/','AdminController@home')->name('admin.home');
});

/* Trainer */
Route::prefix('trainer')->group(function(){
    Route::get('/login','TrainerController@index')->name('trainer.login');
    Route::post('/login','TrainerController@login')->name('trainer.login.submit');
    Route::post('/logout','TrainerController@logout')->name('trainer.logout');
    Route::get('/base','TrainerController@base')->name('trainer.base');
    Route::get('/','TrainerController@home')->name('trainer.home');
});

The reason is because of the $this->middleware('auth:admin') you dedicated the whole AdminController for authenticated users. 原因是因为您使用$this->middleware('auth:admin')将整个AdminController专用于经过身份验证的用户。 So, when you hit the admin url the app keeps redirecting forth and back. 因此,当您点击管理员url时,该应用程序将继续前后重定向。 To fix this add the except method to the middleware to exclude the index method from middle ware protection. 要解决此问题,请在中间件中添加除外方法,以将索引方法从中间件保护中排除。 It Should be $this->middleware('auth:admin')->except(['index']); 应该是$this->middleware('auth:admin')->except(['index']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM