laravel中的Auth认证:
简介
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') }}