1. 程式人生 > >laravel 新增後臺登陸守護器

laravel 新增後臺登陸守護器

後臺不能在一個瀏覽器登陸,下面簡單配置下即可解決這個問題。

設定路由如下:

<?php

/**
 * 後臺路由,從Illuminate\Routing\Router控制器的auth()方法中複製過來的
 */
Route::namespace('Admin')->group(function () { // Authentication Routes... Route::get('login', 'Auth\[email protected]')->name('admin.login'); Route::post('login', 'Auth\[email protected]
'); Route::post('logout', 'Auth\[email protected]')->name('admin.logout'); // Registration Routes... Route::get('register', 'Auth\[email protected]')->name('admin.register'); Route::post('register', 'Auth\[email protected]'); // Password Reset Routes... Route::get('password/reset', 'Auth\
[email protected]
')->name('admin.password.request'); Route::post('password/email', 'Auth\[email protected]')->name('admin.password.email'); Route::get('password/reset/{token}', 'Auth\[email protected]')->name('admin.password.reset'); Route::post('password/reset', 'Auth\[email protected]
'); Route::middleware(["auth:admin"])->group(function () { Route::get('/', '[email protected]')->name('admin'); }); }); <?php /** * 前臺路由,從Illuminate\Routing\Router控制器的auth()方法中複製過來的 */ Route::get('/', function () { return view('welcome'); }); // Authentication Routes... Route::get('login', 'Auth\[email protected]')->name('login'); Route::post('login', 'Auth\[email protected]'); Route::post('logout', 'Auth\[email protected]')->name('logout'); // Registration Routes... Route::get('register', 'Auth\[email protected]')->name('register'); Route::post('register', 'Auth\[email protected]'); // Password Reset Routes... Route::get('password/reset', 'Auth\[email protected]')->name('password.request'); Route::post('password/email', 'Auth\[email protected]')->name('password.email'); Route::get('password/reset/{token}', 'Auth\[email protected]')->name('password.reset'); Route::post('password/reset', 'Auth\[email protected]'); Route::middleware(["auth:web"])->group(function () { Route::get('/home', '[email protected]')->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' => App\User::class, ], 'admins' => [ 'driver' => 'eloquent', 'model' => \App\Models\Admin::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, ], ], ]; 

為後臺所有路由設定字首 App\Providers\RouteServiceProvider:

<?php

namespace App\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider 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 = 'App\Http\Controllers'; /** * 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')); } } 

後臺 App\Http\Controllers\Admin\Auth\LoginController 如下:

<?php

namespace App\Http\Controllers\Admin\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Support\Facades\Auth; 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 \Illuminate\Contracts\Auth\StatefulGuard */ protected function guard() { return Auth::guard('admin'); } } 

前臺 App\Http\Controllers\Auth\LoginController 如下:

<?php

namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; 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'); } } 

App\Http\Middleware\RedirectIfAuthenticated 中介軟體修改 (防止二次登入,與LoginController中的$this->middleware('guest:web')->except('logout') 這裡相呼應,除了退出登入,只要訪問類似登入,註冊,找回密碼的路由時候,都檢查一遍使用者是否登入,登陸了直接跳到登入頁,未登入走auth中介軟體):

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