簡介
Laravel 5.3 的 Auth 認證在 5.2 的基礎上又有一些改變,本文說明如何在 Laravel 5.3 下做不同用戶表的登錄認證。
Auth 認證原理簡述
Laravel 的認證是使用 guard
與 provider
配合完成, guard
負責認證的業務邏輯,認證信息的服務端保存等; provider
負責提供認證信息的持久化數據提供。
請求提交給 guard
, guard
從 provider
里取出數據(類似用戶名、密碼等),驗證輸入數據與服務器端存儲的數據是否吻合。如果提交的數據正確,再做 session 等業務的處理(如有需要)。
認證腳手架
首先我們導入 Laravel 的自帶的認證腳手架
php artisan make:auth
- 1
- 2
執行數據庫遷移:
php artisan migrate
- 1
- 2
修改 Auth 認證的配置文件 config/auth.php
在 gurads 處,添加 admin
guard 用於后台管理員認證
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], ],
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
在 providers 處添加 admins
provider,使用 Admin
模型
'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\User::class, ], 'admins' => [ 'driver' => 'eloquent', 'model' => App\Admin::class, ], ],
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
創建后台管理員模型
我們再創建一個 Admin
模型,用於后台管理員登錄驗證。
php artisan make:model Admin -m
- 1
- 2
-m 參數會同時生成數據庫遷移文件
xxxx_create_admins_table
修改 app/Admin.php
模型文件
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class Admin extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
編輯 xxxx_create_admins_table
文件,后台管理員模型結構與前台用戶差不多,去掉 email
字段,name
字段設為 unique
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAdminsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('admins', function (Blueprint $table) { $table->increments('id'); $table->string('name')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('admins'); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
管理員模型填充數據
定義一個數據模型工廠,在 database/factories/ModelFactory.php
中添加如下代碼
$factory->define(App\Admin::class, function (Faker\Generator $faker) { static $password; return [ 'name' => $faker->firstName, 'password' => $password ?: $password = bcrypt('secret'), 'remember_token' => str_random(10), ]; });
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
使用
Faker
隨機填充用戶名
在 database/seeds
目錄下生成 AdminsTableSeeder.php
文件。
php artisan make:seeder AdminsTableSeeder
- 1
- 2
編輯 database/seeds/AdminsTableSeeder.php
文件的 run
方法,添加3個管理員用戶,密碼為 123456
public function run() { factory('App\Admin', 3)->create([ 'password' => bcrypt('123456') ]); }
- 1
- 2
- 3
- 4
- 5
- 6
在 database/seeds/DatabaseSeeder.php
的 run
方法里調用 AdminsTableSeeder
類
public function run() { $this->call(AdminsTableSeeder::class); }
- 1
- 2
- 3
- 4
執行數據庫遷移命令
php artisan migrate --seed
- 1
- 2
數據庫里會創建 admins 表,並且生成了3條數據
id | name | password | remember_token | create_at | update_at |
---|---|---|---|---|---|
1 | John | $2y$10$AYD4MoW… | 9p7bycJ5Wn | 2016-09-12 11:12:37 | 2016-09-12 11:12:37 |
2 | Ransom | $2y$10$AYD4MoW… | Ct8W5nmTsg | 2016-09-12 11:12:37 | 2016-09-12 11:12:37 |
3 | Dulce | $2y$10$AYD4MoW… | I8RJpxwVrk | 2016-09-12 11:12:37 | 2016-09-12 11:12:37 |
創建后台頁面
創建控制器
php artisan make:controller Admin/LoginController
php artisan make:controller Admin/IndexController
- 1
- 2
- 3
其中, Admin/LoginController
負責登錄邏輯; Admin/IndexController
管理登錄后的首頁。
編輯 Admin/LoginController.php
<?php namespace App\Http\Controllers\Admin; 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 / registration. * * @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.login'); } /** * 使用 admin guard */ protected function guard() { return auth()->guard('admin'); } /** * 重寫驗證時使用的用戶名字段 */ public function username() { return 'name'; } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
編輯 Admin/IndexController.php
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class IndexController extends Controller { /** * 顯示后台管理模板首頁 */ public function index() { return view('admin.index'); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
后台顯示模板
復制 views/layouts/app.blade.php
成 views/layouts/admin.blade.php
編輯后台管理布局模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }} - Admin</title> <!-- Styles --> <link href="/css/app.css" rel="stylesheet"> <!-- Scripts --> <script> window.Laravel = <?php echo json_encode([ 'csrfToken' => csrf_token(), ]); ?> </script> </head> <body> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <!-- Collapsed Hamburger --> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse"> <span class="sr-only">Toggle Navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Branding Image --> <a class="navbar-brand" href="{{ url('/') }}"> {{ config('app.name', 'Laravel') }} </a> </div> <div class="collapse navbar-collapse" id="app-navbar-collapse"> <!-- Left Side Of Navbar --> <ul class="nav navbar-nav"> </ul> <!-- Right Side Of Navbar --> <ul class="nav navbar-nav navbar-right"> <!-- Authentication Links --> @if (auth()->guard('admin')->guest()) <li><a href="{{ url('/admin/login') }}">Login</a></li> @else <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> {{ auth()->guard('admin')->user()->name }} <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <li> <a href="{{ url('/admin/logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> Logout </a> <form id="logout-form" action="{{ url('/admin/logout') }}" method="POST"