zoukankan      html  css  js  c++  java
  • laravel 添加后台登陆守护器

    后台不能在一个浏览器登陆,下面简单配置下即可解决这个问题。

    设置路由如下:

    <?php
    
    /**
     * 后台路由,从IlluminateRoutingRouter控制器的auth()方法中复制过来的
     */
    Route::namespace('Admin')->group(function () {
        // Authentication Routes...
        Route::get('login', 'AuthLoginController@showLoginForm')->name('admin.login');
        Route::post('login', 'AuthLoginController@login');
        Route::post('logout', 'AuthLoginController@logout')->name('admin.logout');
    
    // Registration Routes...
        Route::get('register', 'AuthRegisterController@showRegistrationForm')->name('admin.register');
        Route::post('register', 'AuthRegisterController@register');
    
    // Password Reset Routes...
        Route::get('password/reset', 'AuthForgotPasswordController@showLinkRequestForm')->name('admin.password.request');
        Route::post('password/email', 'AuthForgotPasswordController@sendResetLinkEmail')->name('admin.password.email');
        Route::get('password/reset/{token}', 'AuthResetPasswordController@showResetForm')->name('admin.password.reset');
        Route::post('password/reset', 'AuthResetPasswordController@reset');
    
        Route::middleware(["auth:admin"])->group(function () {
            Route::get('/', 'AdminController@index')->name('admin');
        });
    });
    
    <?php
    
    /**
     * 前台路由,从IlluminateRoutingRouter控制器的auth()方法中复制过来的
     */
    Route::get('/', function () {
        return view('welcome');
    });
    
    // Authentication Routes...
    Route::get('login', 'AuthLoginController@showLoginForm')->name('login');
    Route::post('login', 'AuthLoginController@login');
    Route::post('logout', 'AuthLoginController@logout')->name('logout');
    
    // Registration Routes...
    Route::get('register', 'AuthRegisterController@showRegistrationForm')->name('register');
    Route::post('register', 'AuthRegisterController@register');
    
    // Password Reset Routes...
    Route::get('password/reset', 'AuthForgotPasswordController@showLinkRequestForm')->name('password.request');
    Route::post('password/email', 'AuthForgotPasswordController@sendResetLinkEmail')->name('password.email');
    Route::get('password/reset/{token}', 'AuthResetPasswordController@showResetForm')->name('password.reset');
    Route::post('password/reset', 'AuthResetPasswordController@reset');
    
    Route::middleware(["auth:web"])->group(function () {
        Route::get('/home', 'HomeController@index')->name('home');
    });
    

    设置 config/auth.php:

    <?php
    
    return [
    
        /*
        |--------------------------------------------------------------------------
        | Authentication Defaults
        |--------------------------------------------------------------------------
        |
        | This option controls the default authentication "guard" and password
        | reset options for your application. You may change these defaults
        | as required, but they're a perfect start for most applications.
        |
        */
    
        'defaults' => [
            'guard' => 'web',
            'passwords' => 'users',
        ],
    
        /*
        |--------------------------------------------------------------------------
        | Authentication Guards
        |--------------------------------------------------------------------------
        |
        | Next, you may define every authentication guard for your application.
        | Of course, a great default configuration has been defined for you
        | here which uses session storage and the Eloquent user provider.
        |
        | All authentication drivers have a user provider. This defines how the
        | users are actually retrieved out of your database or other storage
        | mechanisms used by this application to persist your user's data.
        |
        | Supported: "session", "token"
        |
        */
    
        'guards' => [
            'web' => [
                'driver' => 'session',
                'provider' => 'users',
            ],
    
            'admin' => [
                'driver' => 'session',
                'provider' => 'admins',
            ],
    
            'api' => [
                'driver' => 'token',
                'provider' => 'users',
            ],
        ],
    
        /*
        |--------------------------------------------------------------------------
        | User Providers
        |--------------------------------------------------------------------------
        |
        | All authentication drivers have a user provider. This defines how the
        | users are actually retrieved out of your database or other storage
        | mechanisms used by this application to persist your user's data.
        |
        | If you have multiple user tables or models you may configure multiple
        | sources which represent each model / table. These sources may then
        | be assigned to any extra authentication guards you have defined.
        |
        | Supported: "database", "eloquent"
        |
        */
    
        'providers' => [
            'users' => [
                'driver' => 'eloquent',
                'model' => AppUser::class,
            ],
    
            'admins' => [
                'driver' => 'eloquent',
                'model' => AppModelsAdmin::class,
            ],
            // 'users' => [
            //     'driver' => 'database',
            //     'table' => 'users',
            // ],
        ],
    
        /*
        |--------------------------------------------------------------------------
        | Resetting Passwords
        |--------------------------------------------------------------------------
        |
        | You may specify multiple password reset configurations if you have more
        | than one user table or model in the application and you want to have
        | separate password reset settings based on the specific user types.
        |
        | The expire time is the number of minutes that the reset token should be
        | considered valid. This security feature keeps tokens short-lived so
        | they have less time to be guessed. You may change this as needed.
        |
        */
    
        'passwords' => [
            'users' => [
                'provider' => 'users',
                'table' => 'password_resets',
                'expire' => 60,
            ],
        ],
    
    ];
    

    为后台所有路由设置前缀 AppProvidersRouteServiceProvider:

    <?php
    
    namespace AppProviders;
    
    use IlluminateSupportFacadesRoute;
    use IlluminateFoundationSupportProvidersRouteServiceProvider as ServiceProvider;
    
    class RouteServiceProvider extends ServiceProvider
    {
        /**
         * This namespace is applied to your controller routes.
         *
         * In addition, it is set as the URL generator's root namespace.
         *
         * @var string
         */
        protected $namespace = 'AppHttpControllers';
    
        /**
         * Define your route model bindings, pattern filters, etc.
         *
         * @return void
         */
        public function boot()
        {
            //
    
            parent::boot();
        }
    
        /**
         * Define the routes for the application.
         *
         * @return void
         */
        public function map()
        {
            $this->mapApiRoutes();
    
            $this->mapWebRoutes();
    
            // 为后台路由添加前缀
            $this->mapAdminRoutes();
    
            //
        }
    
        /**
         * Define the "web" routes for the application.
         *
         * These routes all receive session state, CSRF protection, etc.
         *
         * @return void
         */
        protected function mapWebRoutes()
        {
            Route::middleware('web')
                 ->namespace($this->namespace)
                 ->group(base_path('routes/web.php'));
        }
    
        /**
         * Define the "api" routes for the application.
         *
         * These routes are typically stateless.
         *
         * @return void
         */
        protected function mapApiRoutes()
        {
            Route::prefix('api')
                 ->middleware('api')
                 ->namespace($this->namespace)
                 ->group(base_path('routes/api.php'));
        }
    
        /**
         * 加入后台路由
         */
        protected function mapAdminRoutes()
        {
            Route::prefix('admin')
                ->middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/admin.php'));
        }
    }
    

    后台 AppHttpControllersAdminAuthLoginController 如下:

    <?php
    
    namespace AppHttpControllersAdminAuth;
    
    use AppHttpControllersController;
    use IlluminateFoundationAuthAuthenticatesUsers;
    use IlluminateSupportFacadesAuth;
    
    class LoginController extends Controller
    {
        /*
        |--------------------------------------------------------------------------
        | Login Controller
        |--------------------------------------------------------------------------
        |
        | This controller handles authenticating users for the application and
        | redirecting them to your home screen. The controller uses a trait
        | to conveniently provide its functionality to your applications.
        |
        */
    
        use AuthenticatesUsers;
    
        /**
         * Where to redirect users after login.
         *
         * @var string
         */
        protected $redirectTo = '/admin';
    
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('guest:admin')->except('logout');
        }
    
        public function showLoginForm()
        {
            return view('admin.auth.login');
        }
    
        /**
         * Get the guard to be used during authentication.
         *
         * @return IlluminateContractsAuthStatefulGuard
         */
        protected function guard()
        {
            return Auth::guard('admin');
        }
    }
    

    前台 AppHttpControllersAuthLoginController 如下:

    <?php
    
    namespace AppHttpControllersAuth;
    
    use AppHttpControllersController;
    use IlluminateFoundationAuthAuthenticatesUsers;
    
    class LoginController extends Controller
    {
        /*
        |--------------------------------------------------------------------------
        | Login Controller
        |--------------------------------------------------------------------------
        |
        | This controller handles authenticating users for the application and
        | redirecting them to your home screen. The controller uses a trait
        | to conveniently provide its functionality to your applications.
        |
        */
    
        use AuthenticatesUsers;
    
        /**
         * Where to redirect users after login.
         *
         * @var string
         */
        protected $redirectTo = '/home';
    
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('guest:web')->except('logout');
        }
    }
    

    AppHttpMiddlewareRedirectIfAuthenticated 中间件修改 (防止二次登录,与LoginController中的$this->middleware('guest:web')->except('logout') 这里相呼应,除了退出登录,只要访问类似登录,注册,找回密码的路由时候,都检查一遍用户是否登录,登陆了直接跳到登录页,未登录走auth中间件):

    <?php
    
    namespace AppHttpMiddleware;
    
    use Closure;
    use IlluminateSupportFacadesAuth;
    
    class RedirectIfAuthenticated
    {
        /**
         * Handle an incoming request.
         *
         * @param  IlluminateHttpRequest  $request
         * @param  Closure  $next
         * @param  string|null  $guard
         * @return mixed
         */
        public function handle($request, Closure $next, $guard = null)
        {
            if ($guard == 'web' && Auth::guard($guard)->check()) {
                return redirect('/home');
            }
    
            if ($guard == 'admin' && Auth::guard($guard)->check()) {
                return redirect('/admin');
            }
    
            return $next($request);
        }
    }
    

    效果:

    file
     
    file
     
    原文地址:https://laravel-china.org/articles/21683
  • 相关阅读:
    ConnectionUtils
    设置组件内容模板和头部模板
    设置idea 代码模板
    Win10 安装流程 Maven
    IDEA: Error:java: 无效的源发行版: 9
    eclipse js的自动提示
    SQLserver SQL语句自动格式化工具的调出
    java计算两个n阶矩阵相乘
    JSP页面输出数据库表格
    threadpool 的配置实用
  • 原文地址:https://www.cnblogs.com/sweetsunnyflower/p/10186639.html
Copyright © 2011-2022 走看看